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());
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();
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 (O(1) Arc clone)
147            self.eval_cache.main_form_snapshot = Some(std::sync::Arc::clone(&new_data));
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                            let cached = if self.table_metadata.contains_key(eval_key) {
436                                self.eval_cache
437                                    .check_table_cache(eval_key, deps)
438                                    .map(|arc| Value::clone(&arc))
439                            } else {
440                                self.eval_cache.check_cache(eval_key, deps)
441                            };
442                            if let Some(cached) = cached {
443                                let pointer_path =
444                                    path_utils::normalize_to_json_pointer(eval_key).into_owned();
445                                batch_hits.push((pointer_path, cached));
446                                true
447                            } else {
448                                false
449                            }
450                        });
451
452                        if all_hit {
453                            // Populate eval_data AND evaluated_schema so both downstream batches
454                            // and get_evaluated_schema callers see the correct per-item values.
455                            // Previously only eval_data was written here, leaving evaluated_schema
456                            // with stale values from the last full-miss evaluation (e.g. the first
457                            // rider), causing all riders to report the same schema outputs.
458                            for (ptr, val) in batch_hits {
459                                self.eval_data.set(&ptr, val.clone());
460                                if let Some(schema_value) = self.evaluated_schema.pointer_mut(&ptr)
461                                {
462                                    *schema_value = val;
463                                }
464                            }
465                        }
466                        // Partial or full miss — fall through to the normal exclusive_clone path below.
467                        // batch_hits is dropped here; cache lookups will repeat but that's cheap.
468                        all_hit
469                    });
470                    if all_cache_hit {
471                        continue;
472                    }
473
474                    // Sequential execution.
475                    // For each formula miss, snapshot_data() gives an O(1) Arc::clone
476                    // as a stable read view. The Arc is dropped before self.eval_data.set()
477                    // so Arc::make_mut always finds rc=1 — zero deep copy, zero latency.
478                    time_block!("      batch sequential eval", {
479                        for eval_key in batch {
480                            if let Some(t) = token {
481                                if t.is_cancelled() {
482                                    return Err("Cancelled".to_string());
483                                }
484                            }
485                            // Filter individual items if paths are provided
486                            if let Some(filter_paths) = normalized_paths {
487                                if !filter_paths.is_empty()
488                                    && !filter_paths.iter().any(|p| {
489                                        eval_key.starts_with(p.as_str())
490                                            || (p.starts_with(eval_key.as_str())
491                                                && !eval_key.contains("/$params/"))
492                                    })
493                                {
494                                    continue;
495                                }
496                            }
497
498                            let pointer_path =
499                                path_utils::normalize_to_json_pointer(eval_key).into_owned();
500
501                            // Cache miss - evaluate
502                            let is_table = self.table_metadata.contains_key(eval_key);
503
504                            if is_table {
505                                time_block!("        table eval", {
506                                    // Snapshot for table read access: Arc::clone is O(1).
507                                    // Scoped so it's dropped before self.eval_data.set() below,
508                                    // keeping self.eval_data.data at rc=1 so Arc::make_mut is free.
509                                    let table_result = {
510                                        let table_scope =
511                                            EvalData::from_arc(self.eval_data.snapshot_data());
512                                        table_evaluate::evaluate_table(
513                                            self,
514                                            eval_key,
515                                            &table_scope,
516                                            token,
517                                        )
518                                        // table_scope dropped here → rc back to 1
519                                    };
520                                    if let Ok((arc_value, external_deps_opt)) = table_result {
521                                        if let Some(external_deps) = external_deps_opt {
522                                            self.eval_cache.store_cache_arc(
523                                                eval_key,
524                                                &external_deps,
525                                                std::sync::Arc::clone(&arc_value),
526                                            );
527                                        }
528
529                                        // NOTE: bump_params_version / bump_data_version for table results
530                                        // is now handled inside store_cache (conditional on value change).
531                                        // The separate bump here was double-counting: store_cache uses T2
532                                        // comparison while this block used eval_data as reference point,
533                                        // causing two version increments per changed table.
534
535                                        let static_key = format!("/$table{}", pointer_path);
536
537                                        Arc::make_mut(&mut self.static_arrays).insert(
538                                            static_key.clone(),
539                                            std::sync::Arc::clone(&arc_value),
540                                        );
541
542                                        self.eval_data.set(&pointer_path, (*arc_value).clone());
543
544                                        let marker =
545                                            serde_json::json!({ "$static_array": static_key });
546                                        self.engine
547                                            .set_static_arrays(Arc::clone(&self.static_arrays));
548
549                                        if let Some(schema_value) =
550                                            self.evaluated_schema.pointer_mut(&pointer_path)
551                                        {
552                                            *schema_value = marker;
553                                        }
554                                    }
555                                });
556                            } else {
557                                let empty_deps = indexmap::IndexSet::new();
558                                let deps = self.dependencies.get(eval_key).unwrap_or(&empty_deps);
559                                let cached_result = self.eval_cache.check_cache(eval_key, &deps);
560
561                                time_block!("        formula eval", {
562                                    if let Some(cached_result) = cached_result {
563                                        // Must still populate eval_data out of cache so subsequent formulas
564                                        // referencing this path in the same iteration can read the exact value
565                                        self.eval_data.set(&pointer_path, cached_result.clone());
566                                        if let Some(schema_value) =
567                                            self.evaluated_schema.pointer_mut(&pointer_path)
568                                        {
569                                            *schema_value = cached_result;
570                                        }
571                                    } else if let Some(logic_id) = self.evaluations.get(eval_key) {
572                                        // snapshot_data() is O(1) Arc::clone — no deep copy.
573                                        // Arc is moved into `snap` and lives only for the
574                                        // engine.run() call, then dropped before set() below.
575                                        // This keeps self.eval_data.data at rc=1 when set()
576                                        // calls Arc::make_mut, so no deep clone ever occurs.
577                                        let val = {
578                                            let snap = self.eval_data.snapshot_data();
579                                            self.engine.run(logic_id, &*snap)
580                                            // snap dropped here → rc back to 1
581                                        };
582                                        match val {
583                                            Ok(val) => {
584                                                let cleaned_val = clean_float_noise_scalar(val);
585                                                let data_path = crate::jsoneval::path_utils::schema_path_to_data_pointer(&pointer_path).into_owned();
586                                                self.eval_cache.store_cache(
587                                                    eval_key,
588                                                    &deps,
589                                                    cleaned_val.clone(),
590                                                );
591
592                                                // Bump data_versions when non-$params field value changes.
593                                                // $params bumps are handled inside store_cache (conditional).
594                                                let old_val = self
595                                                    .eval_data
596                                                    .get(&data_path)
597                                                    .cloned()
598                                                    .unwrap_or(Value::Null);
599                                                if cleaned_val != old_val
600                                                    && !data_path.starts_with("/$params")
601                                                {
602                                                    self.eval_cache.bump_data_version(&data_path);
603                                                }
604
605                                                self.eval_data
606                                                    .set(&pointer_path, cleaned_val.clone());
607                                                if let Some(schema_value) =
608                                                    self.evaluated_schema.pointer_mut(&pointer_path)
609                                                {
610                                                    *schema_value = cleaned_val;
611                                                }
612                                            }
613                                            Err(_) => {
614                                                // Formula failed — ensure no raw $evaluation object leaks.
615                                                // Write null only if the node still holds the unevaluated formula.
616                                                if let Some(node) =
617                                                    self.evaluated_schema.pointer_mut(&pointer_path)
618                                                {
619                                                    if node.is_object()
620                                                        && node.get("$evaluation").is_some()
621                                                    {
622                                                        *node = Value::Null;
623                                                    }
624                                                }
625                                            }
626                                        }
627                                    }
628                                });
629                            }
630                        }
631                    });
632                }
633            });
634
635            // Drop lock before calling evaluate_others
636            drop(_lock);
637
638            // Mark generation stable so the next evaluate_internal call can detect whether
639            // any formula was actually re-stored (via bump_data/params_version) since this run.
640            self.eval_cache.mark_evaluated();
641
642            self.evaluate_others(paths, token);
643
644            Ok(())
645        })
646    }
647
648    pub(crate) fn evaluate_others(
649        &mut self,
650        paths: Option<&[String]>,
651        token: Option<&CancellationToken>,
652    ) {
653        if let Some(t) = token {
654            if t.is_cancelled() {
655                return;
656            }
657        }
658        time_block!("    evaluate_others()", {
659            // Step 1: Evaluate "rules" and "others" categories with caching
660            // Rules are evaluated here so their values are available in evaluated_schema
661            let combined_count = self.rules_evaluations.len() + self.others_evaluations.len();
662            if combined_count > 0 {
663                time_block!("      evaluate rules+others", {
664                    let eval_data_snapshot = self.eval_data.clone();
665
666                    let normalized_paths: Option<Vec<String>> = paths.map(|p_list| {
667                        p_list
668                            .iter()
669                            .flat_map(|p| {
670                                let ptr = path_utils::dot_notation_to_schema_pointer(p);
671                                // Also support version with /properties/ prefix for root match
672                                let with_props = if ptr.starts_with("#/") {
673                                    format!("#/properties/{}", &ptr[2..])
674                                } else {
675                                    ptr.clone()
676                                };
677                                vec![ptr, with_props]
678                            })
679                            .collect()
680                    });
681
682                    // Sequential evaluation
683                    let combined_evals: Vec<&String> = self
684                        .rules_evaluations
685                        .iter()
686                        .chain(self.others_evaluations.iter())
687                        .collect();
688
689                    for eval_key in combined_evals {
690                        if let Some(t) = token {
691                            if t.is_cancelled() {
692                                return;
693                            }
694                        }
695
696                        // // Defer options array evaluation — only the root /options field,
697                        // // not its children (e.g. /options/0/label are still evaluated normally).
698                        // // Call get_field_options() to resolve on demand.
699                        // if eval_key.ends_with("/options") {
700                        //     continue;
701                        // }
702
703                        // Filter items if paths are provided
704                        if let Some(filter_paths) = normalized_paths.as_ref() {
705                            if !filter_paths.is_empty()
706                                && !filter_paths.iter().any(|p| {
707                                    eval_key.starts_with(p.as_str())
708                                        || (p.starts_with(eval_key.as_str())
709                                            && !eval_key.contains("/$params/"))
710                                })
711                            {
712                                continue;
713                            }
714                        }
715
716                        let pointer_path =
717                            path_utils::normalize_to_json_pointer(eval_key).into_owned();
718                        let empty_deps = indexmap::IndexSet::new();
719                        let deps = self.dependencies.get(eval_key).unwrap_or(&empty_deps);
720
721                        if let Some(cached_result) = self.eval_cache.check_cache(eval_key, &deps) {
722                            if let Some(pointer_value) =
723                                self.evaluated_schema.pointer_mut(&pointer_path)
724                            {
725                                if !pointer_path.starts_with("$")
726                                    && pointer_path.contains("/rules/")
727                                    && !pointer_path.ends_with("/value")
728                                {
729                                    if let Some(pointer_obj) = pointer_value.as_object_mut() {
730                                        pointer_obj.remove("$evaluation");
731                                        pointer_obj
732                                            .insert("value".to_string(), cached_result.clone());
733                                    }
734                                } else {
735                                    *pointer_value = cached_result.clone();
736                                }
737                            }
738                            continue;
739                        }
740                        if let Some(logic_id) = self.evaluations.get(eval_key) {
741                            match self.engine.run(logic_id, eval_data_snapshot.data()) {
742                                Ok(val) => {
743                                    let cleaned_val = clean_float_noise_scalar(val);
744                                    self.eval_cache.store_cache(
745                                        eval_key,
746                                        &deps,
747                                        cleaned_val.clone(),
748                                    );
749
750                                    if let Some(pointer_value) =
751                                        self.evaluated_schema.pointer_mut(&pointer_path)
752                                    {
753                                        if !pointer_path.starts_with("$")
754                                            && pointer_path.contains("/rules/")
755                                            && !pointer_path.ends_with("/value")
756                                        {
757                                            match pointer_value.as_object_mut() {
758                                                Some(pointer_obj) => {
759                                                    pointer_obj.remove("$evaluation");
760                                                    pointer_obj
761                                                        .insert("value".to_string(), cleaned_val);
762                                                }
763                                                None => continue,
764                                            }
765                                        } else {
766                                            *pointer_value = cleaned_val;
767                                        }
768                                    }
769                                }
770                                Err(_) => {
771                                    // Formula failed — ensure no raw $evaluation object leaks.
772                                    // Write null only if the node still holds the unevaluated formula.
773                                    if let Some(node) =
774                                        self.evaluated_schema.pointer_mut(&pointer_path)
775                                    {
776                                        if node.is_object() && node.get("$evaluation").is_some() {
777                                            *node = Value::Null;
778                                        }
779                                    }
780                                }
781                            }
782                        }
783                    }
784                });
785            }
786        });
787
788        self.refresh_computed_value_dependents(token);
789        self.evaluate_options_templates(paths);
790
791        self.invalidate_layout_cache();
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}