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::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 /// Attempt the plain-case arena splice for a write of `value_av` at
269 /// `parts`. Covered shape: `parts[0]` resolves to a cached top slot with
270 /// a depth-2 cache; for writes deeper than depth 2, `parts[1]` names an
271 /// *existing* depth-2 child and every deeper segment is a plain
272 /// (non-numeric) object key. Returns `false` when the shape needs the
273 /// owned-rebuild fallback instead.
274 fn try_splice_write_parts(&mut self, parts: &[Arc<str>], value_av: DataValue<'a>) -> bool {
275 if parts.len() < 2 {
276 return false;
277 }
278 // A raw segment that parses as usize takes array-index semantics in
279 // `set_nested_value_parts` — fall back rather than mirror that here.
280 // (`#`-escaped keys never parse: `#20` is the object key "20".)
281 if parts[2..].iter().any(|p| p.parse::<usize>().is_ok()) {
282 return false;
283 }
284
285 let top = strip_hash_prefix(&parts[0]);
286 let Some(top_idx) = self.top_keys.iter().position(|k| *k == top) else {
287 // Write created a brand-new top slot — rare; let the fallback
288 // build it from owned.
289 return false;
290 };
291 let arena = self.arena;
292 let Some(d2) = self.depth2[top_idx].as_mut() else {
293 // Top slot isn't an Object (or has no depth-2 cache) — the owned
294 // write may have no-op'd or reshaped it; fall back.
295 return false;
296 };
297
298 let d2_key = strip_hash_prefix(&parts[1]);
299 let d2_pos = d2.keys.iter().position(|k| *k == d2_key);
300
301 if parts.len() == 2 {
302 // Whole depth-2 slot replace/insert: the eval result IS the new
303 // child value — no owned round-trip needed.
304 match d2_pos {
305 Some(pos) => d2.values[pos] = value_av,
306 None => {
307 d2.keys.push(arena.alloc_str(d2_key));
308 d2.values.push(value_av);
309 }
310 }
311 } else {
312 let Some(pos) = d2_pos else {
313 // First write into a not-yet-cached depth-2 subtree (e.g. the
314 // first mapping into `data.MT103`) — the owned write creates
315 // it; let the fallback arena the fresh subtree once.
316 return false;
317 };
318 let Some(new_subtree) =
319 splice_object_write(arena, d2.values[pos], &parts[2..], value_av)
320 else {
321 // Non-object hop (scalar/array mid-path) — the owned write
322 // no-ops or takes semantics the splice doesn't mirror.
323 return false;
324 };
325 d2.values[pos] = new_subtree;
326 }
327
328 let slice = build_object_slice(arena, &d2.keys, &d2.values);
329 self.top_values[top_idx] = DataValue::Object(slice);
330 true
331 }
332
333 /// Test-only differential check: the live cache must be value- and
334 /// order-identical to a fresh depth-2 rebuild of `owned_ctx`.
335 #[cfg(test)]
336 fn assert_matches_owned(&self, owned_ctx: &OwnedDataValue) {
337 let rebuilt = ArenaContext::from_owned(owned_ctx, self.arena);
338 assert_eq!(
339 self.as_data_value().to_owned(),
340 rebuilt.as_data_value().to_owned(),
341 "arena cache diverged from owned context"
342 );
343 }
344
345 /// Refresh the arena slot(s) for `path` from the current `owned_ctx`,
346 /// without applying any new write. Used when a sync task mutated
347 /// `message.context` directly (e.g. `parse_json` going through legacy
348 /// helpers) and we need the arena to catch up.
349 pub fn refresh_for_path(&mut self, owned_ctx: &OwnedDataValue, path: &str) {
350 self.refresh_after_write(owned_ctx, path);
351 }
352
353 /// Pre-split variant of [`Self::refresh_for_path`] — callers holding
354 /// compiler-populated path parts (parse/publish target paths) skip the
355 /// per-call `str::split`.
356 pub fn refresh_for_path_parts(&mut self, owned_ctx: &OwnedDataValue, parts: &[Arc<str>]) {
357 self.refresh_after_write_parts(owned_ctx, parts);
358 }
359
360 /// Pre-split variant of `refresh_after_write` — same algorithm, no
361 /// per-call `str::split` walk. `parts` retains the original `#` prefix;
362 /// the hash strip is applied here at lookup so the cache key matches
363 /// what `set_nested_value_parts` actually wrote.
364 fn refresh_after_write_parts(&mut self, owned_ctx: &OwnedDataValue, parts: &[Arc<str>]) {
365 let top_raw: &str = match parts.first() {
366 Some(p) if !p.is_empty() => p,
367 _ => {
368 self.rebuild_all_from(owned_ctx);
369 return;
370 }
371 };
372 let top = strip_hash_prefix(top_raw);
373 let depth2_key: Option<&str> = parts.get(1).map(|p| strip_hash_prefix(p));
374 let depth3_key: Option<&str> = parts.get(2).map(|p| strip_hash_prefix(p));
375 self.refresh_after_write_inner(owned_ctx, top, depth2_key, depth3_key);
376 }
377
378 /// Refresh the arena cache after `owned_ctx` was mutated at `path`.
379 fn refresh_after_write(&mut self, owned_ctx: &OwnedDataValue, path: &str) {
380 let mut parts = path.split('.');
381 let top_raw = match parts.next() {
382 Some(p) if !p.is_empty() => p,
383 _ => {
384 self.rebuild_all_from(owned_ctx);
385 return;
386 }
387 };
388 let top = strip_hash_prefix(top_raw);
389 let depth2_key = parts.next().map(strip_hash_prefix);
390 let depth3_key = parts.next().map(strip_hash_prefix);
391 self.refresh_after_write_inner(owned_ctx, top, depth2_key, depth3_key);
392 }
393
394 /// Shared body: walk the cache for `top` and optional `depth2_key`,
395 /// rebuilding only the dirtied slot. `depth3_key` is ignored (the
396 /// depth-3 sub-cache was tried but regressed on the realistic workload —
397 /// per-write d3 cache thrashing exceeded the savings).
398 fn refresh_after_write_inner(
399 &mut self,
400 owned_ctx: &OwnedDataValue,
401 top: &str,
402 depth2_key: Option<&str>,
403 _depth3_key: Option<&str>,
404 ) {
405 let OwnedDataValue::Object(owned_pairs) = owned_ctx else {
406 self.rebuild_all_from(owned_ctx);
407 return;
408 };
409
410 let owned_top_val = owned_pairs.iter().find(|(k, _)| k == top).map(|(_, v)| v);
411
412 let top_idx = self.top_keys.iter().position(|k| *k == top);
413
414 match (owned_top_val, top_idx) {
415 (None, Some(idx)) => {
416 // Top slot was removed from owned ctx — remove from cache.
417 self.top_keys.remove(idx);
418 self.top_values.remove(idx);
419 self.depth2.remove(idx);
420 }
421 (Some(new_val), idx_opt) => {
422 let idx = match idx_opt {
423 Some(i) => i,
424 None => {
425 self.top_keys.push(self.arena.alloc_str(top));
426 self.top_values.push(DataValue::Null);
427 self.depth2.push(None);
428 self.top_keys.len() - 1
429 }
430 };
431
432 match (new_val, depth2_key, &mut self.depth2[idx]) {
433 // Depth-2 write into an existing Object top slot that already
434 // has a depth-2 cache → refresh only the child.
435 (OwnedDataValue::Object(new_children), Some(child_key), Some(d2)) => {
436 if let Some(new_child) = new_children
437 .iter()
438 .find(|(k, _)| k == child_key)
439 .map(|(_, v)| v)
440 {
441 // Replace or insert the single child slot.
442 let child_arena = new_child.to_arena(self.arena);
443 if let Some(pos) = d2.keys.iter().position(|k| *k == child_key) {
444 d2.values[pos] = child_arena;
445 } else {
446 d2.keys.push(self.arena.alloc_str(child_key));
447 d2.values.push(child_arena);
448 }
449 // Also reflect deletions of *other* depth-2 keys
450 // (rare but possible if the write replaced the
451 // whole top object). Cheap O(n) scan.
452 if d2.keys.len() != new_children.len() {
453 // Owned children diverged from our cache —
454 // rebuild the depth-2 cache from owned.
455 self.rebuild_top_slot(new_val, idx);
456 return;
457 }
458 } else {
459 // child_key not found in new owned object — child
460 // was removed. Drop from cache.
461 if let Some(pos) = d2.keys.iter().position(|k| *k == child_key) {
462 d2.keys.remove(pos);
463 d2.values.remove(pos);
464 }
465 }
466 let slice = build_object_slice(self.arena, &d2.keys, &d2.values);
467 self.top_values[idx] = DataValue::Object(slice);
468 }
469 // Top-level (depth-1) write or shape change → rebuild
470 // the whole top slot (cheap relative to a full ctx walk).
471 _ => {
472 self.rebuild_top_slot(new_val, idx);
473 }
474 }
475 }
476 (None, None) => { /* no-op */ }
477 }
478 }
479
480 fn rebuild_top_slot(&mut self, owned: &OwnedDataValue, idx: usize) {
481 match owned {
482 OwnedDataValue::Object(children) => {
483 let mut d2_keys: Vec<&'a str> = Vec::with_capacity(children.len());
484 let mut d2_values: Vec<DataValue<'a>> = Vec::with_capacity(children.len());
485 for (ck, cv) in children {
486 d2_keys.push(self.arena.alloc_str(ck));
487 d2_values.push(cv.to_arena(self.arena));
488 }
489 let slice = build_object_slice(self.arena, &d2_keys, &d2_values);
490 self.top_values[idx] = DataValue::Object(slice);
491 self.depth2[idx] = Some(Depth2Cache {
492 keys: d2_keys,
493 values: d2_values,
494 });
495 }
496 _ => {
497 self.top_values[idx] = owned.to_arena(self.arena);
498 self.depth2[idx] = None;
499 }
500 }
501 }
502
503 /// Last-resort: ditch all cached state and rebuild from scratch. Should be
504 /// rare on normal flows — only triggered if the context shape changes in
505 /// a way the depth-2 cache can't track.
506 fn rebuild_all_from(&mut self, ctx: &OwnedDataValue) {
507 let rebuilt = ArenaContext::from_owned(ctx, self.arena);
508 self.top_keys = rebuilt.top_keys;
509 self.top_values = rebuilt.top_values;
510 self.depth2 = rebuilt.depth2;
511 }
512}
513
514/// Allocate a fresh `(key, value)` slice in the arena. Each
515/// `engine.evaluate` call gets its own slice; subsequent mutations to the
516/// underlying Vecs are independent.
517fn build_object_slice<'a>(
518 arena: &'a Bump,
519 keys: &[&'a str],
520 values: &[DataValue<'a>],
521) -> &'a [(&'a str, DataValue<'a>)] {
522 debug_assert_eq!(keys.len(), values.len());
523 arena.alloc_slice_fill_iter(keys.iter().zip(values.iter()).map(|(k, v)| (*k, *v)))
524}
525
526/// Rebuild only the spine of `current` for a write of `value` at `parts`
527/// (all plain object keys — the caller has excluded numeric segments).
528/// Each level allocates a fresh `(key, value)` slice with the one descended
529/// child replaced: shallow pair copies, no string data copied, no descent
530/// into unchanged siblings. A missing key builds the remaining chain as
531/// nested single-pair Objects, mirroring `set_nested_value_parts`' create
532/// semantics for non-numeric segments. Returns `None` when `current` is not
533/// an Object — those shapes (array hop, scalar overwrite mid-path) take the
534/// owned-rebuild fallback, which mirrors whatever the owned write did.
535fn splice_object_write<'a>(
536 arena: &'a Bump,
537 current: DataValue<'a>,
538 parts: &[Arc<str>],
539 value: DataValue<'a>,
540) -> Option<DataValue<'a>> {
541 let DataValue::Object(pairs) = current else {
542 return None;
543 };
544 let key = strip_hash_prefix(&parts[0]);
545 let pos = pairs.iter().position(|(k, _)| *k == key);
546
547 let new_slice = if parts.len() == 1 {
548 // Terminal level: replace the slot, or append a new pair.
549 match pos {
550 Some(p) => alloc_pairs_with_replaced(arena, pairs, p, value),
551 None => alloc_pairs_with_appended(arena, pairs, arena.alloc_str(key), value),
552 }
553 } else {
554 match pos {
555 Some(p) => {
556 let child = splice_object_write(arena, pairs[p].1, &parts[1..], value)?;
557 alloc_pairs_with_replaced(arena, pairs, p, child)
558 }
559 None => {
560 let chain = build_object_chain(arena, &parts[1..], value);
561 alloc_pairs_with_appended(arena, pairs, arena.alloc_str(key), chain)
562 }
563 }
564 };
565 Some(DataValue::Object(new_slice))
566}
567
568/// Wrap `value` in nested single-pair Objects, innermost-last: for parts
569/// `[a, b]` produces `{a: {b: value}}`. Mirrors the container-creation path
570/// of `set_nested_value_parts` when every segment is a non-numeric key.
571fn build_object_chain<'a>(
572 arena: &'a Bump,
573 parts: &[Arc<str>],
574 value: DataValue<'a>,
575) -> DataValue<'a> {
576 let mut acc = value;
577 for part in parts.iter().rev() {
578 let key: &'a str = arena.alloc_str(strip_hash_prefix(part));
579 let slice = arena.alloc_slice_fill_iter(std::iter::once((key, acc)));
580 acc = DataValue::Object(slice);
581 }
582 acc
583}
584
585/// Fresh slice with `pairs[replace_idx]`'s value swapped for `new_value`.
586fn alloc_pairs_with_replaced<'a>(
587 arena: &'a Bump,
588 pairs: &'a [(&'a str, DataValue<'a>)],
589 replace_idx: usize,
590 new_value: DataValue<'a>,
591) -> &'a [(&'a str, DataValue<'a>)] {
592 arena.alloc_slice_fill_with(pairs.len(), |i| {
593 if i == replace_idx {
594 (pairs[i].0, new_value)
595 } else {
596 pairs[i]
597 }
598 })
599}
600
601/// Fresh slice of `pairs` plus one appended `(key, value)` pair.
602fn alloc_pairs_with_appended<'a>(
603 arena: &'a Bump,
604 pairs: &'a [(&'a str, DataValue<'a>)],
605 key: &'a str,
606 value: DataValue<'a>,
607) -> &'a [(&'a str, DataValue<'a>)] {
608 arena.alloc_slice_fill_with(pairs.len() + 1, |i| {
609 if i < pairs.len() {
610 pairs[i]
611 } else {
612 (key, value)
613 }
614 })
615}
616
617/// Evaluate a workflow or task condition using a cached compiled logic
618/// expression. Returns `true` when `condition_index` is `None` (no condition
619/// is treated as "always run"). Evaluation errors are logged and downgraded
620/// to `false` — a condition that fails to evaluate skips its task/workflow
621/// rather than aborting the whole message.
622pub fn evaluate_condition(
623 engine: &Engine,
624 compiled_condition: Option<&Arc<Logic>>,
625 context: &OwnedDataValue,
626) -> Result<bool> {
627 match compiled_condition {
628 Some(compiled) => match eval_to_owned(engine, compiled, context) {
629 Ok(value) => Ok(matches!(value, OwnedDataValue::Bool(true))),
630 Err(e) => {
631 error!("Failed to evaluate condition: {:?}", e);
632 Ok(false)
633 }
634 },
635 None => Ok(true),
636 }
637}
638
639/// Same as `evaluate_condition` but evaluates against an arena-resident
640/// `DataValue` and an existing `Bump`. Used inside a `with_arena` block
641/// (the workflow sync-stretch path) to avoid re-entering the thread-local
642/// arena `RefCell::borrow_mut`.
643pub fn evaluate_condition_in_arena(
644 engine: &Engine,
645 compiled_condition: Option<&Arc<Logic>>,
646 ctx: DataValue<'_>,
647 arena: &Bump,
648) -> Result<bool> {
649 match compiled_condition {
650 Some(compiled) => match engine.evaluate(compiled, ctx, arena) {
651 Ok(value) => Ok(matches!(value, DataValue::Bool(true))),
652 Err(e) => {
653 error!("Failed to evaluate condition: {:?}", e);
654 Ok(false)
655 }
656 },
657 None => Ok(true),
658 }
659}
660
661#[cfg(test)]
662mod tests {
663 use super::*;
664 use crate::engine::utils::{set_nested_value, set_nested_value_parts};
665 use serde_json::json;
666
667 fn dv(v: serde_json::Value) -> OwnedDataValue {
668 OwnedDataValue::from(&v)
669 }
670
671 fn parts_of(path: &str) -> Vec<Arc<str>> {
672 path.split('.').map(Arc::from).collect()
673 }
674
675 /// Drive a corpus of writes through the write-through path. Every call
676 /// re-validates the cache against a from-scratch rebuild via the
677 /// `#[cfg(test)]` assertion inside `apply_mutation_parts_write_through`,
678 /// so this test fails on any splice/fallback divergence — splice hits
679 /// (deep object paths, `#`-escaped keys, chain creation, depth-2
680 /// replace/insert) and fallback shapes (array segments, scalar mid-path
681 /// no-ops, new top slots) alike.
682 #[test]
683 fn write_through_differential_corpus() {
684 let mut owned = dv(json!({
685 "data": {
686 "input": {"big": {"nested": [1, 2, 3]}, "flag": true},
687 "MT103": {"20": "REF", "72": "existing"},
688 "items": [{"x": 1}, {"x": 2}],
689 "scalar": "leaf"
690 },
691 "metadata": {"processed_at": "t0"},
692 "temp_data": {}
693 }));
694
695 with_arena(|arena| {
696 let mut ctx = ArenaContext::from_owned(&owned, arena);
697
698 let corpus: &[(&str, serde_json::Value)] = &[
699 // Depth-3 replace of an existing key inside a cached subtree.
700 ("data.MT103.20", json!("NEWREF")),
701 // Depth-3 append of a new key.
702 ("data.MT103.23B", json!("CRED")),
703 // Depth-4 with a missing intermediate — chain creation.
704 ("data.MT103.32A.amount", json!(1500.25)),
705 // Depth-4 into the now-existing intermediate.
706 ("data.MT103.32A.currency", json!("USD")),
707 // Deeper chain creation (three missing levels).
708 ("data.MT103.a.b.c", json!({"deep": [1, {"k": "v"}]})),
709 // Overwrite an entire existing sub-object.
710 ("data.MT103.32A", json!({"replaced": true})),
711 // Depth-2 whole-slot replace with an object.
712 ("data.MT103", json!({"fresh": {"start": 1}})),
713 // Depth-2 whole-slot replace with a scalar (drops d2 cache on
714 // next rebuild; subsequent write through it must no-op).
715 ("data.scalar2", json!("plain")),
716 // New depth-2 key inserted into an existing top slot.
717 ("data.MT202", json!({"20": "REF2"})),
718 // Write into a not-yet-cached depth-2 subtree (fallback).
719 ("data.MT205.20", json!("REF5")),
720 // `#`-escaped keys: object keys "20" and "#".
721 ("data.MT103.#20", json!("HASH20")),
722 ("data.MT103.##", json!("HASHKEY")),
723 // Array index segments — fallback shapes.
724 ("data.items.0.x", json!(10)),
725 ("data.items.3", json!({"x": 4})),
726 // Scalar mid-path — owned write no-ops; cache must stay in sync.
727 ("data.scalar.sub.key", json!("ignored")),
728 // Metadata / temp_data writes.
729 ("metadata.progress.workflow_id", json!("wf1")),
730 ("temp_data.uetr", json!("uuid-here")),
731 // Brand-new top-level slot (fallback creates it).
732 ("other_top.x.y", json!(42)),
733 ];
734
735 for (path, val) in corpus {
736 let parts = parts_of(path);
737 let owned_val = dv(val.clone());
738 let value_av = owned_val.to_arena(arena);
739 ctx.apply_mutation_parts_write_through(&mut owned, &parts, value_av, |c| {
740 set_nested_value_parts(c, &parts, owned_val.clone());
741 });
742 }
743
744 // Spot-check a few end states against the owned source of truth.
745 assert_eq!(owned["data"]["MT103"]["20"], dv(json!("HASH20")));
746 assert_eq!(owned["data"]["MT103"]["fresh"]["start"], dv(json!(1)));
747 assert_eq!(owned["data"]["items"][3]["x"], dv(json!(4)));
748 assert_eq!(owned["data"]["scalar"], dv(json!("leaf")));
749 assert_eq!(
750 owned["metadata"]["progress"]["workflow_id"],
751 dv(json!("wf1"))
752 );
753 });
754 }
755
756 /// Interleave reads (as_data_value) with write-throughs to make sure a
757 /// previously handed-out slice never aliases a mutated spine.
758 #[test]
759 fn write_through_reads_see_latest_state() {
760 let mut owned = dv(json!({
761 "data": {"doc": {"a": 1}},
762 "metadata": {},
763 "temp_data": {}
764 }));
765
766 with_arena(|arena| {
767 let mut ctx = ArenaContext::from_owned(&owned, arena);
768
769 for i in 0..10u64 {
770 let key = format!("data.doc.f{i}");
771 let parts = parts_of(&key);
772 let owned_val = OwnedDataValue::from(i);
773 let value_av = owned_val.to_arena(arena);
774 ctx.apply_mutation_parts_write_through(&mut owned, &parts, value_av, |c| {
775 set_nested_value_parts(c, &parts, owned_val.clone());
776 });
777 // A fresh projection after every write must equal owned.
778 assert_eq!(ctx.as_data_value().to_owned(), owned);
779 }
780 });
781 }
782
783 /// The refresh-only path (used by parse_json and the per-task progress
784 /// refresh) must remain consistent when mixed with write-throughs.
785 #[test]
786 fn refresh_and_write_through_interleave() {
787 let mut owned = dv(json!({
788 "data": {},
789 "metadata": {},
790 "temp_data": {}
791 }));
792
793 with_arena(|arena| {
794 let mut ctx = ArenaContext::from_owned(&owned, arena);
795
796 // Simulate parse_json: direct owned write + refresh_for_path.
797 set_nested_value(&mut owned, "data.input", dv(json!({"payload": {"v": 7}})));
798 ctx.refresh_for_path(&owned, "data.input");
799 assert_eq!(ctx.as_data_value().to_owned(), owned);
800
801 // Then map write-throughs landing next to it.
802 let parts = parts_of("data.out.v");
803 let owned_val = dv(json!(7));
804 let value_av = owned_val.to_arena(arena);
805 ctx.apply_mutation_parts_write_through(&mut owned, &parts, value_av, |c| {
806 set_nested_value_parts(c, &parts, owned_val.clone());
807 });
808
809 // Simulate the progress write + narrow refresh.
810 set_nested_value(
811 &mut owned,
812 "metadata.progress",
813 dv(json!({"task_id": "t1"})),
814 );
815 ctx.refresh_for_path(&owned, "metadata.progress");
816 assert_eq!(ctx.as_data_value().to_owned(), owned);
817 });
818 }
819}