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., computed fields, calculated formulas) 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., `/items/sub_items`)
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            // (e.g., aggregate formulas over items) 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-item results being reused for a different item
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 significant overhead per subform item on large payloads.
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 item's values) when no deps changed — causing get_evaluated_schema_subform
277        // to return wrong values for all but the last-evaluated item.
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            let _static_guard =
301                self.engine.bind_static_arrays_scope(Arc::clone(&self.static_arrays));
302
303            // Normalize paths to schema pointers for correct filtering
304            let normalized_paths_storage; // Keep alive
305            let normalized_paths = if let Some(p_list) = paths {
306                normalized_paths_storage = p_list
307                    .iter()
308                    .flat_map(|p| {
309                        let normalized = if p.starts_with("#/") {
310                            p.to_string()
311                        } else if p.starts_with('/') {
312                            format!("#{}", p)
313                        } else {
314                            format!("#/{}", p.replace('.', "/"))
315                        };
316                        vec![normalized]
317                    })
318                    .collect::<Vec<_>>();
319                Some(normalized_paths_storage.as_slice())
320            } else {
321                None
322            };
323
324            // Borrow sorted_evaluations via Arc (avoid deep-cloning Vec<Vec<String>>)
325            let eval_batches = self.sorted_evaluations.clone();
326
327            // Process each batch - sequentially
328            // Batches are processed sequentially to maintain dependency order
329            // Process value evaluations (simple computed fields with no dependencies)
330            let eval_data_values = self.eval_data.clone();
331            time_block!("      evaluate values", {
332                for eval_key in self.value_evaluations.iter() {
333                    if let Some(t) = token {
334                        if t.is_cancelled() {
335                            return Err("Cancelled".to_string());
336                        }
337                    }
338                    // Skip if has dependencies (handled in sorted batches with correct ordering)
339                    if let Some(deps) = self.dependencies.get(eval_key) {
340                        if !deps.is_empty() {
341                            continue;
342                        }
343                    }
344
345                    // Filter items if paths are provided
346                    if let Some(filter_paths) = normalized_paths {
347                        if !filter_paths.is_empty()
348                            && !filter_paths.iter().any(|p| {
349                                eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())
350                            })
351                        {
352                            continue;
353                        }
354                    }
355
356                    let pointer_path = path_utils::normalize_to_json_pointer(eval_key).into_owned();
357                    let empty_deps = indexmap::IndexSet::new();
358                    let deps = self.dependencies.get(eval_key).unwrap_or(&empty_deps);
359
360                    // Cache hit check
361                    if let Some(_cached_result) = self.eval_cache.check_cache(eval_key, deps) {
362                        continue;
363                    }
364
365                    // Cache miss - evaluate
366                    if let Some(logic_id) = self.evaluations.get(eval_key) {
367                        match self.engine.run(logic_id, eval_data_values.data()) {
368                            Ok(val) => {
369                                let cleaned_val = clean_float_noise_scalar(val);
370                                self.eval_cache
371                                    .store_cache(eval_key, deps, cleaned_val.clone());
372
373                                if let Some(pointer_value) =
374                                    self.evaluated_schema.pointer_mut(&pointer_path)
375                                {
376                                    *pointer_value = cleaned_val;
377                                }
378                            }
379                            Err(_) => {
380                                // Formula failed — ensure no raw $evaluation object leaks.
381                                // Write null only if the node still holds the unevaluated formula.
382                                if let Some(node) = self.evaluated_schema.pointer_mut(&pointer_path)
383                                {
384                                    if node.is_object() && node.get("$evaluation").is_some() {
385                                        *node = Value::Null;
386                                    }
387                                }
388                            }
389                        }
390                    }
391                }
392            });
393
394            time_block!("    process batches", {
395                for batch in eval_batches.iter() {
396                    if let Some(t) = token {
397                        if t.is_cancelled() {
398                            return Err("Cancelled".to_string());
399                        }
400                    }
401                    // Skip empty batches
402                    if batch.is_empty() {
403                        continue;
404                    }
405
406                    // Check if we can skip this entire batch optimization
407                    let batch_skipped = time_block!("      batch filter check", {
408                        if let Some(filter_paths) = normalized_paths {
409                            if !filter_paths.is_empty() {
410                                let batch_has_match = batch.iter().any(|eval_key| {
411                                    filter_paths.iter().any(|p| {
412                                        eval_key.starts_with(p.as_str())
413                                            || (p.starts_with(eval_key.as_str())
414                                                && !eval_key.contains("/$params/"))
415                                    })
416                                });
417                                !batch_has_match
418                            } else {
419                                false
420                            }
421                        } else {
422                            false
423                        }
424                    });
425                    if batch_skipped {
426                        continue;
427                    }
428
429                    // Fast path: try to resolve every eval_key in this batch from cache.
430                    // If all hit, skip the expensive exclusive_clone() of the full eval_data tree.
431                    // This is critical for subforms where eval_data contains the full parent payload.
432                    let all_cache_hit = time_block!("      batch cache fast path", {
433                        let mut batch_hits: Vec<(String, Value)> = Vec::with_capacity(batch.len());
434                        let all_hit = batch.iter().all(|eval_key| {
435                            let empty_deps = indexmap::IndexSet::new();
436                            let deps = self.dependencies.get(eval_key).unwrap_or(&empty_deps);
437                            let cached = if self.table_metadata.contains_key(eval_key) {
438                                self.eval_cache
439                                    .check_table_cache(eval_key, deps)
440                                    .map(|arc| Value::clone(&arc))
441                            } else {
442                                self.eval_cache.check_cache(eval_key, deps)
443                            };
444                            if let Some(cached) = cached {
445                                let pointer_path =
446                                    path_utils::normalize_to_json_pointer(eval_key).into_owned();
447                                batch_hits.push((pointer_path, cached));
448                                true
449                            } else {
450                                false
451                            }
452                        });
453
454                        if all_hit {
455                            // Populate eval_data AND evaluated_schema so both downstream batches
456                            // and get_evaluated_schema callers see the correct per-item values.
457                            // Previously only eval_data was written here, leaving evaluated_schema
458                            // with stale values from the last full-miss evaluation (e.g. the first
459                            // rider), causing all riders to report the same schema outputs.
460                            for (ptr, val) in batch_hits {
461                                self.eval_data.set(&ptr, val.clone());
462                                if let Some(schema_value) = self.evaluated_schema.pointer_mut(&ptr)
463                                {
464                                    *schema_value = val;
465                                }
466                            }
467                        }
468                        // Partial or full miss — fall through to the normal exclusive_clone path below.
469                        // batch_hits is dropped here; cache lookups will repeat but that's cheap.
470                        all_hit
471                    });
472                    if all_cache_hit {
473                        continue;
474                    }
475
476                    // Sequential execution.
477                    // For each formula miss, snapshot_data() gives an O(1) Arc::clone
478                    // as a stable read view. The Arc is dropped before self.eval_data.set()
479                    // so Arc::make_mut always finds rc=1 — zero deep copy, zero latency.
480                    time_block!("      batch sequential eval", {
481                        for eval_key in batch {
482                            if let Some(t) = token {
483                                if t.is_cancelled() {
484                                    return Err("Cancelled".to_string());
485                                }
486                            }
487                            // Filter individual items if paths are provided
488                            if let Some(filter_paths) = normalized_paths {
489                                if !filter_paths.is_empty()
490                                    && !filter_paths.iter().any(|p| {
491                                        eval_key.starts_with(p.as_str())
492                                            || (p.starts_with(eval_key.as_str())
493                                                && !eval_key.contains("/$params/"))
494                                    })
495                                {
496                                    continue;
497                                }
498                            }
499
500                            let pointer_path =
501                                path_utils::normalize_to_json_pointer(eval_key).into_owned();
502
503                            // Cache miss - evaluate
504                            let is_table = self.table_metadata.contains_key(eval_key);
505
506                            if is_table {
507                                time_block!("        table eval", {
508                                    // Snapshot for table read access: Arc::clone is O(1).
509                                    // Scoped so it's dropped before self.eval_data.set() below,
510                                    // keeping self.eval_data.data at rc=1 so Arc::make_mut is free.
511                                    let table_result = {
512                                        let table_scope =
513                                            EvalData::from_arc(self.eval_data.snapshot_data());
514                                        table_evaluate::evaluate_table(
515                                            self,
516                                            eval_key,
517                                            &table_scope,
518                                            token,
519                                        )
520                                        // table_scope dropped here → rc back to 1
521                                    };
522                                    if let Ok((arc_value, external_deps_opt)) = table_result {
523                                        if let Some(external_deps) = external_deps_opt {
524                                            self.eval_cache.store_cache_arc(
525                                                eval_key,
526                                                &external_deps,
527                                                std::sync::Arc::clone(&arc_value),
528                                            );
529                                        }
530
531                                        // NOTE: bump_params_version / bump_data_version for table results
532                                        // is now handled inside store_cache (conditional on value change).
533                                        // The separate bump here was double-counting: store_cache uses T2
534                                        // comparison while this block used eval_data as reference point,
535                                        // causing two version increments per changed table.
536
537                                        let static_key = format!("/$table{}", pointer_path);
538
539                                        Arc::make_mut(&mut self.static_arrays).insert(
540                                            static_key.clone(),
541                                            std::sync::Arc::clone(&arc_value),
542                                        );
543
544                                        self.eval_data.set(&pointer_path, (*arc_value).clone());
545
546                                        let marker =
547                                            serde_json::json!({ "$static_array": static_key });
548                                        self.engine
549                                            .set_static_arrays(Arc::clone(&self.static_arrays));
550
551                                        if let Some(schema_value) =
552                                            self.evaluated_schema.pointer_mut(&pointer_path)
553                                        {
554                                            *schema_value = marker;
555                                        }
556                                    }
557                                });
558                            } else {
559                                let empty_deps = indexmap::IndexSet::new();
560                                let deps = self.dependencies.get(eval_key).unwrap_or(&empty_deps);
561                                let cached_result = self.eval_cache.check_cache(eval_key, &deps);
562
563                                time_block!("        formula eval", {
564                                    if let Some(cached_result) = cached_result {
565                                        // Must still populate eval_data out of cache so subsequent formulas
566                                        // referencing this path in the same iteration can read the exact value
567                                        self.eval_data.set(&pointer_path, cached_result.clone());
568                                        if let Some(schema_value) =
569                                            self.evaluated_schema.pointer_mut(&pointer_path)
570                                        {
571                                            *schema_value = cached_result;
572                                        }
573                                    } else if let Some(logic_id) = self.evaluations.get(eval_key) {
574                                        // snapshot_data() is O(1) Arc::clone — no deep copy.
575                                        // Arc is moved into `snap` and lives only for the
576                                        // engine.run() call, then dropped before set() below.
577                                        // This keeps self.eval_data.data at rc=1 when set()
578                                        // calls Arc::make_mut, so no deep clone ever occurs.
579                                        let val = {
580                                            let snap = self.eval_data.snapshot_data();
581                                            self.engine.run(logic_id, &*snap)
582                                            // snap dropped here → rc back to 1
583                                        };
584                                        match val {
585                                            Ok(val) => {
586                                                let cleaned_val = clean_float_noise_scalar(val);
587                                                let data_path = crate::jsoneval::path_utils::schema_path_to_data_pointer(&pointer_path).into_owned();
588                                                self.eval_cache.store_cache(
589                                                    eval_key,
590                                                    &deps,
591                                                    cleaned_val.clone(),
592                                                );
593
594                                                // Bump data_versions when non-$params field value changes.
595                                                // $params bumps are handled inside store_cache (conditional).
596                                                let old_val = self
597                                                    .eval_data
598                                                    .get(&data_path)
599                                                    .cloned()
600                                                    .unwrap_or(Value::Null);
601                                                if cleaned_val != old_val
602                                                    && !data_path.starts_with("/$params")
603                                                {
604                                                    self.eval_cache.bump_data_version(&data_path);
605                                                }
606
607                                                self.eval_data
608                                                    .set(&pointer_path, cleaned_val.clone());
609                                                if let Some(schema_value) =
610                                                    self.evaluated_schema.pointer_mut(&pointer_path)
611                                                {
612                                                    *schema_value = cleaned_val;
613                                                }
614                                            }
615                                            Err(_) => {
616                                                // Formula failed — ensure no raw $evaluation object leaks.
617                                                // Write null only if the node still holds the unevaluated formula.
618                                                if let Some(node) =
619                                                    self.evaluated_schema.pointer_mut(&pointer_path)
620                                                {
621                                                    if node.is_object()
622                                                        && node.get("$evaluation").is_some()
623                                                    {
624                                                        *node = Value::Null;
625                                                    }
626                                                }
627                                            }
628                                        }
629                                    }
630                                });
631                            }
632                        }
633                    });
634                }
635            });
636
637            // Drop lock before calling evaluate_others
638            drop(_lock);
639
640            // Mark generation stable so the next evaluate_internal call can detect whether
641            // any formula was actually re-stored (via bump_data/params_version) since this run.
642            self.eval_cache.mark_evaluated();
643
644            self.evaluate_others(paths, token);
645
646            Ok(())
647        })
648    }
649
650    pub(crate) fn evaluate_others(
651        &mut self,
652        paths: Option<&[String]>,
653        token: Option<&CancellationToken>,
654    ) {
655        if let Some(t) = token {
656            if t.is_cancelled() {
657                return;
658            }
659        }
660        time_block!("    evaluate_others()", {
661            // Step 1: Evaluate "rules" and "others" categories with caching
662            // Rules are evaluated here so their values are available in evaluated_schema
663            let combined_count = self.rules_evaluations.len() + self.others_evaluations.len();
664            if combined_count > 0 {
665                time_block!("      evaluate rules+others", {
666                    let eval_data_snapshot = self.eval_data.clone();
667
668                    let normalized_paths: Option<Vec<String>> = paths.map(|p_list| {
669                        p_list
670                            .iter()
671                            .flat_map(|p| {
672                                let ptr = path_utils::dot_notation_to_schema_pointer(p);
673                                // Also support version with /properties/ prefix for root match
674                                let with_props = if ptr.starts_with("#/") {
675                                    format!("#/properties/{}", &ptr[2..])
676                                } else {
677                                    ptr.clone()
678                                };
679                                vec![ptr, with_props]
680                            })
681                            .collect()
682                    });
683
684                    // Sequential evaluation
685                    let combined_evals: Vec<&String> = self
686                        .rules_evaluations
687                        .iter()
688                        .chain(self.others_evaluations.iter())
689                        .collect();
690
691                    for eval_key in combined_evals {
692                        if let Some(t) = token {
693                            if t.is_cancelled() {
694                                return;
695                            }
696                        }
697
698                        // // Defer options array evaluation — only the root /options field,
699                        // // not its children (e.g. /options/0/label are still evaluated normally).
700                        // // Call get_field_options() to resolve on demand.
701                        // if eval_key.ends_with("/options") {
702                        //     continue;
703                        // }
704
705                        // Filter items if paths are provided
706                        if let Some(filter_paths) = normalized_paths.as_ref() {
707                            if !filter_paths.is_empty()
708                                && !filter_paths.iter().any(|p| {
709                                    eval_key.starts_with(p.as_str())
710                                        || (p.starts_with(eval_key.as_str())
711                                            && !eval_key.contains("/$params/"))
712                                })
713                            {
714                                continue;
715                            }
716                        }
717
718                        let pointer_path =
719                            path_utils::normalize_to_json_pointer(eval_key).into_owned();
720                        let empty_deps = indexmap::IndexSet::new();
721                        let deps = self.dependencies.get(eval_key).unwrap_or(&empty_deps);
722
723                        if let Some(cached_result) = self.eval_cache.check_cache(eval_key, &deps) {
724                            if let Some(pointer_value) =
725                                self.evaluated_schema.pointer_mut(&pointer_path)
726                            {
727                                if !pointer_path.starts_with("$")
728                                    && pointer_path.contains("/rules/")
729                                    && !pointer_path.ends_with("/value")
730                                {
731                                    if let Some(pointer_obj) = pointer_value.as_object_mut() {
732                                        pointer_obj.remove("$evaluation");
733                                        pointer_obj
734                                            .insert("value".to_string(), cached_result.clone());
735                                    }
736                                } else {
737                                    *pointer_value = cached_result.clone();
738                                }
739                            }
740                            continue;
741                        }
742                        if let Some(logic_id) = self.evaluations.get(eval_key) {
743                            match self.engine.run(logic_id, eval_data_snapshot.data()) {
744                                Ok(val) => {
745                                    let cleaned_val = clean_float_noise_scalar(val);
746                                    self.eval_cache.store_cache(
747                                        eval_key,
748                                        &deps,
749                                        cleaned_val.clone(),
750                                    );
751
752                                    if let Some(pointer_value) =
753                                        self.evaluated_schema.pointer_mut(&pointer_path)
754                                    {
755                                        if !pointer_path.starts_with("$")
756                                            && pointer_path.contains("/rules/")
757                                            && !pointer_path.ends_with("/value")
758                                        {
759                                            match pointer_value.as_object_mut() {
760                                                Some(pointer_obj) => {
761                                                    pointer_obj.remove("$evaluation");
762                                                    pointer_obj
763                                                        .insert("value".to_string(), cleaned_val);
764                                                }
765                                                None => continue,
766                                            }
767                                        } else {
768                                            *pointer_value = cleaned_val;
769                                        }
770                                    }
771                                }
772                                Err(_) => {
773                                    // Formula failed — ensure no raw $evaluation object leaks.
774                                    // Write null only if the node still holds the unevaluated formula.
775                                    if let Some(node) =
776                                        self.evaluated_schema.pointer_mut(&pointer_path)
777                                    {
778                                        if node.is_object() && node.get("$evaluation").is_some() {
779                                            *node = Value::Null;
780                                        }
781                                    }
782                                }
783                            }
784                        }
785                    }
786                });
787            }
788        });
789
790        self.refresh_computed_value_dependents(token);
791        self.evaluate_options_templates(paths);
792
793        self.invalidate_layout_cache();
794    }
795
796    /// Re-evaluate direct dependents of computed fields against a temporary data overlay.
797    /// Computed values are exposed only for this refresh; shared form data, cache entries and
798    /// version trackers remain untouched, preventing subform/table cascade contamination.
799    fn refresh_computed_value_dependents(&mut self, token: Option<&CancellationToken>) {
800        let computed_values: Vec<(String, Value)> = self
801            .evaluations
802            .keys()
803            .filter_map(|key| {
804                let field_path = key.strip_suffix("/value")?;
805                if !field_path.contains("/properties/") || key.contains("/rules/") {
806                    return None;
807                }
808                let schema_pointer = path_utils::normalize_to_json_pointer(key);
809                let value = self.evaluated_schema.pointer(&schema_pointer)?;
810                if value.is_object() && value.get("$evaluation").is_some() {
811                    return None;
812                }
813                Some((
814                    path_utils::schema_path_to_data_pointer(field_path).into_owned(),
815                    value.clone(),
816                ))
817            })
818            .collect();
819        if computed_values.is_empty() {
820            return;
821        }
822
823        let mut overlay = EvalData::new(self.eval_data.snapshot_data_clone());
824        let mut changed = indexmap::IndexSet::new();
825        for (data_path, value) in computed_values {
826            if overlay.get(&data_path) != Some(&value) {
827                overlay.set(&data_path, value);
828                changed.insert(data_path);
829            }
830        }
831        if changed.is_empty() {
832            return;
833        }
834
835        let targets: Vec<String> = self
836            .evaluations
837            .keys()
838            .filter(|key| {
839                !key.contains("/dependents/")
840                    && !key.contains("/$params/")
841                    && !self.tables.keys().any(|table| key.starts_with(table))
842                    && self.dependencies.get(*key).is_some_and(|dependencies| {
843                        dependencies.iter().any(|dependency| {
844                            changed.contains(
845                                path_utils::schema_path_to_data_pointer(dependency).as_ref(),
846                            )
847                        })
848                    })
849            })
850            .cloned()
851            .collect();
852
853        for key in targets {
854            if token.is_some_and(CancellationToken::is_cancelled) {
855                return;
856            }
857            let Some(logic_id) = self.evaluations.get(&key) else {
858                continue;
859            };
860            let Ok(value) = self.engine.run(logic_id, overlay.data()) else {
861                continue;
862            };
863            let pointer = path_utils::normalize_to_json_pointer(&key);
864            if let Some(node) = self.evaluated_schema.pointer_mut(&pointer) {
865                let value = clean_float_noise_scalar(value);
866                if pointer.contains("/rules/") && !pointer.ends_with("/value") {
867                    if let Some(rule) = node.as_object_mut() {
868                        rule.remove("$evaluation");
869                        rule.insert("value".to_string(), value);
870                    }
871                } else {
872                    *node = value;
873                }
874            }
875        }
876    }
877
878    /// Evaluate options URL templates (handles {variable} patterns) — called on demand from get_field_options
879    #[allow(dead_code)]
880    pub(crate) fn evaluate_options_templates(&mut self, paths: Option<&[String]>) {
881        // Use pre-collected options templates from parsing (Arc clone is cheap)
882        let templates_to_eval = self.options_templates.clone();
883
884        // Evaluate each template
885        for (path, template_str, params_path) in templates_to_eval.iter() {
886            // Filter items if paths are provided
887            // 'path' here is the schema path to the field (dot notation or similar, need to check)
888            // It seems to be schema pointer based on usage in other methods
889            if let Some(filter_paths) = paths {
890                if !filter_paths.is_empty()
891                    && !filter_paths
892                        .iter()
893                        .any(|p| path.starts_with(p.as_str()) || p.starts_with(path.as_str()))
894                {
895                    continue;
896                }
897            }
898
899            if let Some(params) = self.evaluated_schema.pointer(&params_path) {
900                if let Ok(evaluated) = self.evaluate_template(&template_str, params) {
901                    if let Some(target) = self.evaluated_schema.pointer_mut(&path) {
902                        *target = Value::String(evaluated);
903                    }
904                }
905            }
906        }
907    }
908
909    /// Evaluate a template string like "api/users/{id}" with params
910    pub(crate) fn evaluate_template(
911        &self,
912        template: &str,
913        params: &Value,
914    ) -> Result<String, String> {
915        let mut result = template.to_string();
916
917        // Simple template evaluation: replace {key} with params.key
918        if let Value::Object(params_map) = params {
919            for (key, value) in params_map {
920                let placeholder = format!("{{{}}}", key);
921                if let Some(str_val) = value.as_str() {
922                    result = result.replace(&placeholder, str_val);
923                } else {
924                    // Convert non-string values to strings
925                    result = result.replace(&placeholder, &value.to_string());
926                }
927            }
928        }
929
930        Ok(result)
931    }
932}