Skip to main content

json_eval_rs/jsoneval/
evaluate.rs

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