Skip to main content

json_eval_rs/jsoneval/
evaluate.rs

1use std::sync::Arc;
2
3use super::JSONEval;
4use crate::jsoneval::cancellation::CancellationToken;
5use crate::jsoneval::eval_data::EvalData;
6use crate::jsoneval::json_parser;
7use crate::jsoneval::path_utils;
8use crate::jsoneval::table_evaluate;
9use crate::time_block;
10use crate::utils::clean_float_noise_scalar;
11
12use serde_json::Value;
13
14/// Returns `true` if `new_item` (raw user input) is identity-compatible with `old_item`
15/// (snapshot that may contain computed formula outputs alongside raw input fields).
16///
17/// A full `==` comparison fails when `old_item` has extra keys written by formula evaluation
18/// (e.g., `wop_rider_premi`, `first_prem`) that are absent from the raw `new_item`. This helper
19/// compares only the fields present in `new_item`, ignoring extra keys in `old_item`:
20///
21/// - If both are objects: every key in `new` must match the same key in `old`.
22/// - Otherwise: standard equality (covers Null, scalar, array cases).
23///
24/// Used by `invalidate_subform_caches_on_structural_change` to detect genuine order/identity
25/// shifts without false positives from computed formula output fields in the snapshot.
26fn items_same_input_identity(old: Option<&Value>, new: Option<&Value>) -> bool {
27    match (old, new) {
28        (Some(Value::Object(old_map)), Some(Value::Object(new_map))) => new_map
29            .iter()
30            .all(|(k, new_val)| old_map.get(k).map_or(false, |old_val| old_val == new_val)),
31        (old, new) => old == new,
32    }
33}
34
35impl JSONEval {
36    /// Evaluate the schema with the given data and context.
37    ///
38    /// # Arguments
39    ///
40    /// * `data` - The data to evaluate.
41    /// * `context` - The context to evaluate.
42    ///
43    /// # Returns
44    ///
45    /// A `Result` indicating success or an error message.
46    pub fn evaluate(
47        &mut self,
48        data: &str,
49        context: Option<&str>,
50        paths: Option<&[String]>,
51        token: Option<&CancellationToken>,
52    ) -> Result<(), String> {
53        if let Some(t) = token {
54            if t.is_cancelled() {
55                return Err("Cancelled".to_string());
56            }
57        }
58        time_block!("evaluate() [total]", {
59            // Use SIMD-accelerated JSON parsing
60            // Parse and update data/context
61            let data_value = time_block!("  parse data", { json_parser::parse_json_str(data)? });
62            let context_value = time_block!("  parse context", {
63                if let Some(ctx) = context {
64                    json_parser::parse_json_str(ctx)?
65                } else {
66                    Value::Object(serde_json::Map::new())
67                }
68            });
69            self.evaluate_internal_with_new_data(data_value, context_value, paths, token)
70        })
71    }
72
73    /// Internal helper to evaluate with all data/context provided as Values.
74    /// `pub(crate)` so the cache-swap path in `evaluate_subform` can call it directly
75    /// after swapping the parent cache in, bypassing the string-parsing overhead.
76    pub(crate) fn evaluate_internal_with_new_data(
77        &mut self,
78        data: Value,
79        context: Value,
80        paths: Option<&[String]>,
81        token: Option<&CancellationToken>,
82    ) -> Result<(), String> {
83        time_block!("  evaluate_internal_with_new_data", {
84            // Reuse the previously stored snapshot as `old_data` to avoid an O(n) deep clone
85            // on every main-form evaluation call.
86            let has_previous_eval = self.eval_cache.main_form_snapshot.is_some();
87            let old_data = self
88                .eval_cache
89                .main_form_snapshot
90                .take()
91                .unwrap_or_else(|| self.eval_data.snapshot_data_clone());
92
93            let old_context = self
94                .eval_data
95                .data()
96                .get("$context")
97                .cloned()
98                .unwrap_or(Value::Null);
99
100            // Store data, context and replace in eval_data (clone once instead of twice)
101            self.data = data.clone();
102            self.context = context.clone();
103            time_block!("  replace_data_and_context", {
104                self.eval_data.replace_data_and_context(data, context);
105            });
106
107            let new_data = self.eval_data.snapshot_data_clone();
108            let new_context = self
109                .eval_data
110                .data()
111                .get("$context")
112                .cloned()
113                .unwrap_or(Value::Null);
114
115            if has_previous_eval
116                && old_data == new_data
117                && old_context == new_context
118                && paths.is_none()
119            {
120                // Perfect cache hit for unmodified payload: fully skip tree traversal.
121                // Restore snapshot since nothing changed.
122                self.eval_cache.main_form_snapshot = Some(new_data);
123                return Ok(());
124            }
125
126            // Seed subform caches from loaded data.
127            for (subform_path, subform) in &mut self.subforms {
128                let subform_ptr =
129                    crate::jsoneval::path_utils::normalize_to_json_pointer(subform_path);
130                if let Some(items) = new_data.pointer(&subform_ptr).and_then(|v| v.as_array()) {
131                    for (idx, item_val) in items.iter().enumerate() {
132                        self.eval_cache.ensure_active_item_cache(idx);
133                        if let Some(c) = self.eval_cache.subform_caches.get_mut(&idx) {
134                            c.item_snapshot = item_val.clone();
135                        }
136                        subform.eval_cache.ensure_active_item_cache(idx);
137                        if let Some(c) = subform.eval_cache.subform_caches.get_mut(&idx) {
138                            c.item_snapshot = item_val.clone();
139                        }
140                    }
141                }
142            }
143
144            self.eval_cache
145                .store_snapshot_and_diff_versions(&old_data, &new_data);
146            // Save snapshot for the next evaluation cycle (avoids one snapshot_data_clone() call)
147            self.eval_cache.main_form_snapshot = Some(new_data.clone());
148
149            // Invalidate subform caches after structural changes.
150            self.invalidate_subform_caches_on_structural_change(&old_data, &new_data);
151
152            // Skip external traversal when cached dependencies are fresh.
153            if paths.is_none() && !self.eval_cache.needs_full_evaluation() {
154                self.evaluate_others(paths, token);
155                return Ok(());
156            }
157
158            // Apply visible defaults before final formula pass.
159            self.evaluate_internal(paths, token)?;
160            if self.apply_visible_static_defaults() {
161                self.evaluate_internal(paths, token)?;
162            }
163            Ok(())
164        })
165    }
166
167    /// Detect structural changes in subform arrays between `old_data` and `new_data`
168    /// and evict stale caches accordingly.
169    pub(crate) fn invalidate_subform_caches_on_structural_change(
170        &mut self,
171        old_data: &Value,
172        new_data: &Value,
173    ) {
174        for (subform_path, _) in &self.subforms {
175            // Resolve the data pointer for this subform
176            // (e.g., `/illustration/product_benefit/riders`)
177            let subform_ptr =
178                crate::jsoneval::path_utils::schema_path_to_data_pointer(subform_path).to_string();
179
180            let old_items = old_data.pointer(&subform_ptr).and_then(Value::as_array);
181            let new_items = new_data.pointer(&subform_ptr).and_then(Value::as_array);
182
183            let old_len = old_items.map(Vec::len).unwrap_or(0);
184            let new_len = new_items.map(Vec::len).unwrap_or(0);
185            let min_len = old_len.min(new_len);
186
187            // Detect reordered overlapping items.
188            let identities_shifted = (0..min_len).any(|i| {
189                let old_item = old_items.and_then(|a| a.get(i));
190                let new_item = new_items.and_then(|a| a.get(i));
191                !items_same_input_identity(old_item, new_item)
192            });
193
194            if old_len == new_len && !identities_shifted {
195                continue; // No structural change for this subform
196            }
197
198            // Build local subform path prefix.
199            let field_key = subform_ptr
200                .split('/')
201                .next_back()
202                .unwrap_or(subform_ptr.as_str());
203            let subform_dep_prefix = format!("/{}/", field_key);
204
205            // Evict affected T2 entries.
206            let mut evicted_paths: Vec<String> = Vec::new();
207            self.eval_cache.entries.retain(|eval_key, entry| {
208                let has_subform_dep = entry
209                    .dep_versions
210                    .keys()
211                    .any(|dep| dep.starts_with(&subform_dep_prefix));
212
213                if has_subform_dep {
214                    let normalized =
215                        crate::jsoneval::path_utils::schema_path_to_data_pointer(eval_key);
216                    evicted_paths.push(normalized.into_owned());
217                    false // remove entry
218                } else {
219                    true // keep
220                }
221            });
222
223            // Bump params_versions for every evicted T2 entry so downstream $params formulas
224            // (SA_WOP_RIDER, TOTAL_WOP_SA, etc.) correctly miss their caches.
225            for path in &evicted_paths {
226                self.eval_cache
227                    .params_versions
228                    .bump(path, "invalidate_subform_caches_on_structural_change");
229            }
230
231            // Clear T1 per-item caches for indices where item identity has shifted.
232            // This prevents stale per-rider results being reused for a different rider
233            // occupying the same array slot after a reorder.
234            for idx in 0..min_len {
235                let old_item = old_items.and_then(|a| a.get(idx));
236                let new_item = new_items.and_then(|a| a.get(idx));
237                if !items_same_input_identity(old_item, new_item) {
238                    if let Some(c) = self.eval_cache.subform_caches.get_mut(&idx) {
239                        c.entries.clear();
240                        c.data_versions = crate::jsoneval::eval_cache::VersionTracker::new();
241                    }
242                }
243            }
244            // Prune T1 caches for indices that no longer exist (removed items)
245            self.eval_cache.prune_subform_caches(new_len);
246
247            if !evicted_paths.is_empty() || old_len != new_len {
248                self.eval_cache.eval_generation += 1;
249            }
250        }
251    }
252
253    /// Fast variant of `evaluate_internal_with_new_data` for the cache-swap path.
254    ///
255    /// The caller (e.g. `run_subform_pass` / `evaluate_subform_item`) has **already**:
256    /// 1. Called `replace_data_and_context` on `subform.eval_data` with the merged payload.
257    /// 2. Computed the item-level diff and bumped `subform_caches[idx].data_versions` accordingly.
258    /// 3. Swapped the parent cache into `subform.eval_cache` so Tier 2 entries are visible.
259    /// 4. Set `active_item_index = Some(idx)` on the swapped-in cache.
260    ///
261    /// Skipping the expensive `snapshot_data_clone()` × 2 and `diff_and_update_versions`
262    /// saves ~40–80ms per rider on a 5 MB parent payload.
263    pub(crate) fn evaluate_internal_pre_diffed(
264        &mut self,
265        paths: Option<&[String]>,
266        token: Option<&CancellationToken>,
267    ) -> Result<(), String> {
268        debug_assert!(
269            self.eval_cache.active_item_index.is_some(),
270            "evaluate_internal_pre_diffed called without active_item_index — \
271             caller must set up the cache-swap before calling this method"
272        );
273
274        // Always delegate to evaluate_internal so that evaluated_schema is populated correctly
275        // for every item. The previous generation-based skip here left evaluated_schema stale
276        // (with the prior rider's values) when no deps changed — causing get_evaluated_schema_subform
277        // to return wrong values for all but the last-evaluated rider.
278        //
279        // evaluate_internal's all-hit fast path (lines ~314–338) handles the no-change case
280        // efficiently: it writes eval_data + evaluated_schema per formula from T1 cache and
281        // skips the expensive formula engine entirely.
282        self.evaluate_internal(paths, token)
283    }
284
285    /// Internal evaluate that can be called when data is already set
286    /// This avoids double-locking and unnecessary data cloning for re-evaluation from evaluate_dependents
287    pub(crate) fn evaluate_internal(
288        &mut self,
289        paths: Option<&[String]>,
290        token: Option<&CancellationToken>,
291    ) -> Result<(), String> {
292        if let Some(t) = token {
293            if t.is_cancelled() {
294                return Err("Cancelled".to_string());
295            }
296        }
297        time_block!("  evaluate_internal() [total]", {
298            // Acquire lock for synchronous execution
299            let _lock = self.eval_lock.lock().unwrap();
300
301            // Normalize paths to schema pointers for correct filtering
302            let normalized_paths_storage; // Keep alive
303            let normalized_paths = if let Some(p_list) = paths {
304                normalized_paths_storage = p_list
305                    .iter()
306                    .flat_map(|p| {
307                        let normalized = if p.starts_with("#/") {
308                            p.to_string()
309                        } else if p.starts_with('/') {
310                            format!("#{}", p)
311                        } else {
312                            format!("#/{}", p.replace('.', "/"))
313                        };
314                        vec![normalized]
315                    })
316                    .collect::<Vec<_>>();
317                Some(normalized_paths_storage.as_slice())
318            } else {
319                None
320            };
321
322            // Borrow sorted_evaluations via Arc (avoid deep-cloning Vec<Vec<String>>)
323            let eval_batches = self.sorted_evaluations.clone();
324
325            // Process each batch - sequentially
326            // Batches are processed sequentially to maintain dependency order
327            // Process value evaluations (simple computed fields with no dependencies)
328            let eval_data_values = self.eval_data.clone();
329            time_block!("      evaluate values", {
330                for eval_key in self.value_evaluations.iter() {
331                    if let Some(t) = token {
332                        if t.is_cancelled() {
333                            return Err("Cancelled".to_string());
334                        }
335                    }
336                    // Skip if has dependencies (handled in sorted batches with correct ordering)
337                    if let Some(deps) = self.dependencies.get(eval_key) {
338                        if !deps.is_empty() {
339                            continue;
340                        }
341                    }
342
343                    // Filter items if paths are provided
344                    if let Some(filter_paths) = normalized_paths {
345                        if !filter_paths.is_empty()
346                            && !filter_paths.iter().any(|p| {
347                                eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())
348                            })
349                        {
350                            continue;
351                        }
352                    }
353
354                    let pointer_path = path_utils::normalize_to_json_pointer(eval_key).into_owned();
355                    let empty_deps = indexmap::IndexSet::new();
356                    let deps = self.dependencies.get(eval_key).unwrap_or(&empty_deps);
357
358                    // Cache hit check
359                    if let Some(_cached_result) = self.eval_cache.check_cache(eval_key, deps) {
360                        continue;
361                    }
362
363                    // Cache miss - evaluate
364                    if let Some(logic_id) = self.evaluations.get(eval_key) {
365                        match self.engine.run(logic_id, eval_data_values.data()) {
366                            Ok(val) => {
367                                let cleaned_val = clean_float_noise_scalar(val);
368                                self.eval_cache
369                                    .store_cache(eval_key, deps, cleaned_val.clone());
370
371                                if let Some(pointer_value) =
372                                    self.evaluated_schema.pointer_mut(&pointer_path)
373                                {
374                                    *pointer_value = cleaned_val;
375                                }
376                            }
377                            Err(_) => {
378                                // Formula failed — ensure no raw $evaluation object leaks.
379                                // Write null only if the node still holds the unevaluated formula.
380                                if let Some(node) = self.evaluated_schema.pointer_mut(&pointer_path)
381                                {
382                                    if node.is_object() && node.get("$evaluation").is_some() {
383                                        *node = Value::Null;
384                                    }
385                                }
386                            }
387                        }
388                    }
389                }
390            });
391
392            time_block!("    process batches", {
393                for batch in eval_batches.iter() {
394                    if let Some(t) = token {
395                        if t.is_cancelled() {
396                            return Err("Cancelled".to_string());
397                        }
398                    }
399                    // Skip empty batches
400                    if batch.is_empty() {
401                        continue;
402                    }
403
404                    // Check if we can skip this entire batch optimization
405                    let batch_skipped = time_block!("      batch filter check", {
406                        if let Some(filter_paths) = normalized_paths {
407                            if !filter_paths.is_empty() {
408                                let batch_has_match = batch.iter().any(|eval_key| {
409                                    filter_paths.iter().any(|p| {
410                                        eval_key.starts_with(p.as_str())
411                                            || (p.starts_with(eval_key.as_str())
412                                                && !eval_key.contains("/$params/"))
413                                    })
414                                });
415                                !batch_has_match
416                            } else {
417                                false
418                            }
419                        } else {
420                            false
421                        }
422                    });
423                    if batch_skipped {
424                        continue;
425                    }
426
427                    // Fast path: try to resolve every eval_key in this batch from cache.
428                    // If all hit, skip the expensive exclusive_clone() of the full eval_data tree.
429                    // This is critical for subforms where eval_data contains the full parent payload.
430                    let all_cache_hit = time_block!("      batch cache fast path", {
431                        let mut batch_hits: Vec<(String, Value)> = Vec::with_capacity(batch.len());
432                        let all_hit = batch.iter().all(|eval_key| {
433                            let empty_deps = indexmap::IndexSet::new();
434                            let deps = self.dependencies.get(eval_key).unwrap_or(&empty_deps);
435                            if let Some(cached) = self.eval_cache.check_cache(eval_key, deps) {
436                                let pointer_path =
437                                    path_utils::normalize_to_json_pointer(eval_key).into_owned();
438                                batch_hits.push((pointer_path, cached));
439                                true
440                            } else {
441                                false
442                            }
443                        });
444
445                        if all_hit {
446                            // Populate eval_data AND evaluated_schema so both downstream batches
447                            // and get_evaluated_schema callers see the correct per-item values.
448                            // Previously only eval_data was written here, leaving evaluated_schema
449                            // with stale values from the last full-miss evaluation (e.g. the first
450                            // rider), causing all riders to report the same schema outputs.
451                            for (ptr, val) in batch_hits {
452                                self.eval_data.set(&ptr, val.clone());
453                                if let Some(schema_value) = self.evaluated_schema.pointer_mut(&ptr)
454                                {
455                                    *schema_value = val;
456                                }
457                            }
458                        }
459                        // Partial or full miss — fall through to the normal exclusive_clone path below.
460                        // batch_hits is dropped here; cache lookups will repeat but that's cheap.
461                        all_hit
462                    });
463                    if all_cache_hit {
464                        continue;
465                    }
466
467                    // Sequential execution.
468                    // For each formula miss, snapshot_data() gives an O(1) Arc::clone
469                    // as a stable read view. The Arc is dropped before self.eval_data.set()
470                    // so Arc::make_mut always finds rc=1 — zero deep copy, zero latency.
471                    time_block!("      batch sequential eval", {
472                        for eval_key in batch {
473                            if let Some(t) = token {
474                                if t.is_cancelled() {
475                                    return Err("Cancelled".to_string());
476                                }
477                            }
478                            // Filter individual items if paths are provided
479                            if let Some(filter_paths) = normalized_paths {
480                                if !filter_paths.is_empty()
481                                    && !filter_paths.iter().any(|p| {
482                                        eval_key.starts_with(p.as_str())
483                                            || (p.starts_with(eval_key.as_str())
484                                                && !eval_key.contains("/$params/"))
485                                    })
486                                {
487                                    continue;
488                                }
489                            }
490
491                            let pointer_path =
492                                path_utils::normalize_to_json_pointer(eval_key).into_owned();
493
494                            // Cache miss - evaluate
495                            let is_table = self.table_metadata.contains_key(eval_key);
496
497                            if is_table {
498                                time_block!("        table eval", {
499                                    // Snapshot for table read access: Arc::clone is O(1).
500                                    // Scoped so it's dropped before self.eval_data.set() below,
501                                    // keeping self.eval_data.data at rc=1 so Arc::make_mut is free.
502                                    let table_result = {
503                                        let table_scope =
504                                            EvalData::from_arc(self.eval_data.snapshot_data());
505                                        table_evaluate::evaluate_table(
506                                            self,
507                                            eval_key,
508                                            &table_scope,
509                                            token,
510                                        )
511                                        // table_scope dropped here → rc back to 1
512                                    };
513                                    if let Ok((rows, external_deps_opt)) = table_result {
514                                        let result_val = Value::Array(rows);
515                                        if let Some(external_deps) = external_deps_opt {
516                                            self.eval_cache.store_cache(
517                                                eval_key,
518                                                &external_deps,
519                                                result_val.clone(),
520                                            );
521                                        }
522
523                                        // NOTE: bump_params_version / bump_data_version for table results
524                                        // is now handled inside store_cache (conditional on value change).
525                                        // The separate bump here was double-counting: store_cache uses T2
526                                        // comparison while this block used eval_data as reference point,
527                                        // causing two version increments per changed table.
528
529                                        let static_key = format!("/$table{}", pointer_path);
530                                        let arc_value = std::sync::Arc::new(result_val);
531
532                                        Arc::make_mut(&mut self.static_arrays).insert(
533                                            static_key.clone(),
534                                            std::sync::Arc::clone(&arc_value),
535                                        );
536
537                                        self.eval_data.set(&pointer_path, Value::clone(&arc_value));
538
539                                        let marker =
540                                            serde_json::json!({ "$static_array": static_key });
541                                        if let Some(schema_value) =
542                                            self.evaluated_schema.pointer_mut(&pointer_path)
543                                        {
544                                            *schema_value = marker;
545                                        }
546                                    }
547                                });
548                            } else {
549                                let empty_deps = indexmap::IndexSet::new();
550                                let deps = self.dependencies.get(eval_key).unwrap_or(&empty_deps);
551                                let cached_result = self.eval_cache.check_cache(eval_key, &deps);
552
553                                time_block!("        formula eval", {
554                                    if let Some(cached_result) = cached_result {
555                                        // Must still populate eval_data out of cache so subsequent formulas
556                                        // referencing this path in the same iteration can read the exact value
557                                        self.eval_data.set(&pointer_path, cached_result.clone());
558                                        if let Some(schema_value) =
559                                            self.evaluated_schema.pointer_mut(&pointer_path)
560                                        {
561                                            *schema_value = cached_result;
562                                        }
563                                    } else if let Some(logic_id) = self.evaluations.get(eval_key) {
564                                        // snapshot_data() is O(1) Arc::clone — no deep copy.
565                                        // Arc is moved into `snap` and lives only for the
566                                        // engine.run() call, then dropped before set() below.
567                                        // This keeps self.eval_data.data at rc=1 when set()
568                                        // calls Arc::make_mut, so no deep clone ever occurs.
569                                        let val = {
570                                            let snap = self.eval_data.snapshot_data();
571                                            self.engine.run(logic_id, &*snap)
572                                            // snap dropped here → rc back to 1
573                                        };
574                                        match val {
575                                            Ok(val) => {
576                                                let cleaned_val = clean_float_noise_scalar(val);
577                                                let data_path = crate::jsoneval::path_utils::schema_path_to_data_pointer(&pointer_path).into_owned();
578                                                self.eval_cache.store_cache(
579                                                    eval_key,
580                                                    &deps,
581                                                    cleaned_val.clone(),
582                                                );
583
584                                                // Bump data_versions when non-$params field value changes.
585                                                // $params bumps are handled inside store_cache (conditional).
586                                                let old_val = self
587                                                    .eval_data
588                                                    .get(&data_path)
589                                                    .cloned()
590                                                    .unwrap_or(Value::Null);
591                                                if cleaned_val != old_val
592                                                    && !data_path.starts_with("/$params")
593                                                {
594                                                    self.eval_cache.bump_data_version(&data_path);
595                                                }
596
597                                                self.eval_data
598                                                    .set(&pointer_path, cleaned_val.clone());
599                                                if let Some(schema_value) =
600                                                    self.evaluated_schema.pointer_mut(&pointer_path)
601                                                {
602                                                    *schema_value = cleaned_val;
603                                                }
604                                            }
605                                            Err(_) => {
606                                                // Formula failed — ensure no raw $evaluation object leaks.
607                                                // Write null only if the node still holds the unevaluated formula.
608                                                if let Some(node) =
609                                                    self.evaluated_schema.pointer_mut(&pointer_path)
610                                                {
611                                                    if node.is_object()
612                                                        && node.get("$evaluation").is_some()
613                                                    {
614                                                        *node = Value::Null;
615                                                    }
616                                                }
617                                            }
618                                        }
619                                    }
620                                });
621                            }
622                        }
623                    });
624                }
625            });
626
627            // Drop lock before calling evaluate_others
628            drop(_lock);
629
630            // Mark generation stable so the next evaluate_internal call can detect whether
631            // any formula was actually re-stored (via bump_data/params_version) since this run.
632            self.eval_cache.mark_evaluated();
633
634            self.evaluate_others(paths, token);
635
636            Ok(())
637        })
638    }
639
640    pub(crate) fn evaluate_others(
641        &mut self,
642        paths: Option<&[String]>,
643        token: Option<&CancellationToken>,
644    ) {
645        if let Some(t) = token {
646            if t.is_cancelled() {
647                return;
648            }
649        }
650        time_block!("    evaluate_others()", {
651            // Step 1: Evaluate "rules" and "others" categories with caching
652            // Rules are evaluated here so their values are available in evaluated_schema
653            let combined_count = self.rules_evaluations.len() + self.others_evaluations.len();
654            if combined_count > 0 {
655                time_block!("      evaluate rules+others", {
656                    let eval_data_snapshot = self.eval_data.clone();
657
658                    let normalized_paths: Option<Vec<String>> = paths.map(|p_list| {
659                        p_list
660                            .iter()
661                            .flat_map(|p| {
662                                let ptr = path_utils::dot_notation_to_schema_pointer(p);
663                                // Also support version with /properties/ prefix for root match
664                                let with_props = if ptr.starts_with("#/") {
665                                    format!("#/properties/{}", &ptr[2..])
666                                } else {
667                                    ptr.clone()
668                                };
669                                vec![ptr, with_props]
670                            })
671                            .collect()
672                    });
673
674                    // Sequential evaluation
675                    let combined_evals: Vec<&String> = self
676                        .rules_evaluations
677                        .iter()
678                        .chain(self.others_evaluations.iter())
679                        .collect();
680
681                    for eval_key in combined_evals {
682                        if let Some(t) = token {
683                            if t.is_cancelled() {
684                                return;
685                            }
686                        }
687
688                        // // Defer options array evaluation — only the root /options field,
689                        // // not its children (e.g. /options/0/label are still evaluated normally).
690                        // // Call get_field_options() to resolve on demand.
691                        // if eval_key.ends_with("/options") {
692                        //     continue;
693                        // }
694
695                        // Filter items if paths are provided
696                        if let Some(filter_paths) = normalized_paths.as_ref() {
697                            if !filter_paths.is_empty()
698                                && !filter_paths.iter().any(|p| {
699                                    eval_key.starts_with(p.as_str())
700                                        || (p.starts_with(eval_key.as_str())
701                                            && !eval_key.contains("/$params/"))
702                                })
703                            {
704                                continue;
705                            }
706                        }
707
708                        let pointer_path =
709                            path_utils::normalize_to_json_pointer(eval_key).into_owned();
710                        let empty_deps = indexmap::IndexSet::new();
711                        let deps = self.dependencies.get(eval_key).unwrap_or(&empty_deps);
712
713                        if let Some(cached_result) = self.eval_cache.check_cache(eval_key, &deps) {
714                            if let Some(pointer_value) =
715                                self.evaluated_schema.pointer_mut(&pointer_path)
716                            {
717                                if !pointer_path.starts_with("$")
718                                    && pointer_path.contains("/rules/")
719                                    && !pointer_path.ends_with("/value")
720                                {
721                                    if let Some(pointer_obj) = pointer_value.as_object_mut() {
722                                        pointer_obj.remove("$evaluation");
723                                        pointer_obj
724                                            .insert("value".to_string(), cached_result.clone());
725                                    }
726                                } else {
727                                    *pointer_value = cached_result.clone();
728                                }
729                            }
730                            continue;
731                        }
732                        if let Some(logic_id) = self.evaluations.get(eval_key) {
733                            match self.engine.run(logic_id, eval_data_snapshot.data()) {
734                                Ok(val) => {
735                                    let cleaned_val = clean_float_noise_scalar(val);
736                                    self.eval_cache.store_cache(
737                                        eval_key,
738                                        &deps,
739                                        cleaned_val.clone(),
740                                    );
741
742                                    if let Some(pointer_value) =
743                                        self.evaluated_schema.pointer_mut(&pointer_path)
744                                    {
745                                        if !pointer_path.starts_with("$")
746                                            && pointer_path.contains("/rules/")
747                                            && !pointer_path.ends_with("/value")
748                                        {
749                                            match pointer_value.as_object_mut() {
750                                                Some(pointer_obj) => {
751                                                    pointer_obj.remove("$evaluation");
752                                                    pointer_obj
753                                                        .insert("value".to_string(), cleaned_val);
754                                                }
755                                                None => continue,
756                                            }
757                                        } else {
758                                            *pointer_value = cleaned_val;
759                                        }
760                                    }
761                                }
762                                Err(_) => {
763                                    // Formula failed — ensure no raw $evaluation object leaks.
764                                    // Write null only if the node still holds the unevaluated formula.
765                                    if let Some(node) =
766                                        self.evaluated_schema.pointer_mut(&pointer_path)
767                                    {
768                                        if node.is_object() && node.get("$evaluation").is_some() {
769                                            *node = Value::Null;
770                                        }
771                                    }
772                                }
773                            }
774                        }
775                    }
776                });
777            }
778        });
779
780        self.refresh_computed_value_dependents(token);
781        self.evaluate_options_templates(paths);
782
783        // Resolve refs and visibility from current evaluated schema every evaluation.
784        // Rust Value refs are copies, so this state cannot be restored from an old overlay
785        // or persisted by mutating evaluated_schema as legacy JavaScript did.
786        time_block!("      resolve_layout", {
787            let _ = self.resolve_layout(false);
788        });
789
790        // Layout state was rebuilt above. Overlay consumers may reuse it only until next run.
791        self.resolved_layout_cache = None;
792    }
793
794    /// Re-evaluate direct dependents of computed fields against a temporary data overlay.
795    /// Computed values are exposed only for this refresh; shared form data, cache entries and
796    /// version trackers remain untouched, preventing subform/table cascade contamination.
797    fn refresh_computed_value_dependents(&mut self, token: Option<&CancellationToken>) {
798        let computed_values: Vec<(String, Value)> = self
799            .evaluations
800            .keys()
801            .filter_map(|key| {
802                let field_path = key.strip_suffix("/value")?;
803                if !field_path.contains("/properties/") || key.contains("/rules/") {
804                    return None;
805                }
806                let schema_pointer = path_utils::normalize_to_json_pointer(key);
807                let value = self.evaluated_schema.pointer(&schema_pointer)?;
808                if value.is_object() && value.get("$evaluation").is_some() {
809                    return None;
810                }
811                Some((
812                    path_utils::schema_path_to_data_pointer(field_path).into_owned(),
813                    value.clone(),
814                ))
815            })
816            .collect();
817        if computed_values.is_empty() {
818            return;
819        }
820
821        let mut overlay = EvalData::new(self.eval_data.snapshot_data_clone());
822        let mut changed = indexmap::IndexSet::new();
823        for (data_path, value) in computed_values {
824            if overlay.get(&data_path) != Some(&value) {
825                overlay.set(&data_path, value);
826                changed.insert(data_path);
827            }
828        }
829        if changed.is_empty() {
830            return;
831        }
832
833        let targets: Vec<String> = self
834            .evaluations
835            .keys()
836            .filter(|key| {
837                !key.contains("/dependents/")
838                    && !key.contains("/$params/")
839                    && !self.tables.keys().any(|table| key.starts_with(table))
840                    && self.dependencies.get(*key).is_some_and(|dependencies| {
841                        dependencies.iter().any(|dependency| {
842                            changed.contains(
843                                path_utils::schema_path_to_data_pointer(dependency).as_ref(),
844                            )
845                        })
846                    })
847            })
848            .cloned()
849            .collect();
850
851        for key in targets {
852            if token.is_some_and(CancellationToken::is_cancelled) {
853                return;
854            }
855            let Some(logic_id) = self.evaluations.get(&key) else {
856                continue;
857            };
858            let Ok(value) = self.engine.run(logic_id, overlay.data()) else {
859                continue;
860            };
861            let pointer = path_utils::normalize_to_json_pointer(&key);
862            if let Some(node) = self.evaluated_schema.pointer_mut(&pointer) {
863                let value = clean_float_noise_scalar(value);
864                if pointer.contains("/rules/") && !pointer.ends_with("/value") {
865                    if let Some(rule) = node.as_object_mut() {
866                        rule.remove("$evaluation");
867                        rule.insert("value".to_string(), value);
868                    }
869                } else {
870                    *node = value;
871                }
872            }
873        }
874    }
875
876    /// Evaluate options URL templates (handles {variable} patterns) — called on demand from get_field_options
877    #[allow(dead_code)]
878    pub(crate) fn evaluate_options_templates(&mut self, paths: Option<&[String]>) {
879        // Use pre-collected options templates from parsing (Arc clone is cheap)
880        let templates_to_eval = self.options_templates.clone();
881
882        // Evaluate each template
883        for (path, template_str, params_path) in templates_to_eval.iter() {
884            // Filter items if paths are provided
885            // 'path' here is the schema path to the field (dot notation or similar, need to check)
886            // It seems to be schema pointer based on usage in other methods
887            if let Some(filter_paths) = paths {
888                if !filter_paths.is_empty()
889                    && !filter_paths
890                        .iter()
891                        .any(|p| path.starts_with(p.as_str()) || p.starts_with(path.as_str()))
892                {
893                    continue;
894                }
895            }
896
897            if let Some(params) = self.evaluated_schema.pointer(&params_path) {
898                if let Ok(evaluated) = self.evaluate_template(&template_str, params) {
899                    if let Some(target) = self.evaluated_schema.pointer_mut(&path) {
900                        *target = Value::String(evaluated);
901                    }
902                }
903            }
904        }
905    }
906
907    /// Evaluate a template string like "api/users/{id}" with params
908    pub(crate) fn evaluate_template(
909        &self,
910        template: &str,
911        params: &Value,
912    ) -> Result<String, String> {
913        let mut result = template.to_string();
914
915        // Simple template evaluation: replace {key} with params.key
916        if let Value::Object(params_map) = params {
917            for (key, value) in params_map {
918                let placeholder = format!("{{{}}}", key);
919                if let Some(str_val) = value.as_str() {
920                    result = result.replace(&placeholder, str_val);
921                } else {
922                    // Convert non-string values to strings
923                    result = result.replace(&placeholder, &value.to_string());
924                }
925            }
926        }
927
928        Ok(result)
929    }
930}