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, false);
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
185
186        for (subform_path, _) in &self.subforms {
187            // Resolve the data pointer for this subform
188            // (e.g., `/illustration/product_benefit/riders`)
189            let subform_ptr = crate::jsoneval::path_utils::schema_path_to_data_pointer(subform_path).to_string();
190
191            let old_items = old_data.pointer(&subform_ptr).and_then(Value::as_array);
192            let new_items = new_data.pointer(&subform_ptr).and_then(Value::as_array);
193
194            let old_len = old_items.map(Vec::len).unwrap_or(0);
195            let new_len = new_items.map(Vec::len).unwrap_or(0);
196            let min_len = old_len.min(new_len);
197
198            // Detect identity shift in the overlapping index range using subset comparison.
199            // We check whether the raw input fields of new_items[i] all match old_items[i],
200            // ignoring extra computed keys that only exist in the old snapshot.
201            let identities_shifted = (0..min_len).any(|i| {
202                let old_item = old_items.and_then(|a| a.get(i));
203                let new_item = new_items.and_then(|a| a.get(i));
204                !items_same_input_identity(old_item, new_item)
205            });
206
207            if old_len == new_len && !identities_shifted {
208                continue; // No structural change for this subform
209            }
210
211            // Build the subform-local dep-path prefix stored in T2 dep_versions
212            // (e.g., `/riders/` for a riders subform). T2 dep keys are normalized data
213            // paths — never schema paths — so only one prefix is needed.
214            let field_key = subform_ptr
215                .split('/')
216                .next_back()
217                .unwrap_or(subform_ptr.as_str());
218            let subform_dep_prefix = format!("/{}/", field_key);
219
220            // Evict T2 global entries whose deps include any subform-local path.
221            // `retain` evicts inline (no intermediate Vec allocation).
222            // Collect the normalized path of each evicted key for the params_versions bump.
223            let mut evicted_paths: Vec<String> = Vec::new();
224            self.eval_cache.entries.retain(|eval_key, entry| {
225                let has_subform_dep = entry
226                    .dep_versions
227                    .keys()
228                    .any(|dep| dep.starts_with(&subform_dep_prefix));
229
230                if has_subform_dep {
231                    let normalized = 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.params_versions.bump(path, "invalidate_subform_caches_on_structural_change");
243            }
244
245            // Clear T1 per-item caches for indices where item identity has shifted.
246            // This prevents stale per-rider results being reused for a different rider
247            // occupying the same array slot after a reorder.
248            for idx in 0..min_len {
249                let old_item = old_items.and_then(|a| a.get(idx));
250                let new_item = new_items.and_then(|a| a.get(idx));
251                if !items_same_input_identity(old_item, new_item) {
252                    if let Some(c) = self.eval_cache.subform_caches.get_mut(&idx) {
253                        c.entries.clear();
254                        c.data_versions = crate::jsoneval::eval_cache::VersionTracker::new();
255                    }
256                }
257            }
258            // Prune T1 caches for indices that no longer exist (removed items)
259            self.eval_cache.prune_subform_caches(new_len);
260
261            if !evicted_paths.is_empty() || old_len != new_len {
262                self.eval_cache.eval_generation += 1;
263            }
264        }
265    }
266
267    /// Fast variant of `evaluate_internal_with_new_data` for the cache-swap path.
268    ///
269    /// The caller (e.g. `run_subform_pass` / `evaluate_subform_item`) has **already**:
270    /// 1. Called `replace_data_and_context` on `subform.eval_data` with the merged payload.
271    /// 2. Computed the item-level diff and bumped `subform_caches[idx].data_versions` accordingly.
272    /// 3. Swapped the parent cache into `subform.eval_cache` so Tier 2 entries are visible.
273    /// 4. Set `active_item_index = Some(idx)` on the swapped-in cache.
274    ///
275    /// Skipping the expensive `snapshot_data_clone()` × 2 and `diff_and_update_versions`
276    /// saves ~40–80ms per rider on a 5 MB parent payload.
277    pub(crate) fn evaluate_internal_pre_diffed(
278        &mut self,
279        paths: Option<&[String]>,
280        token: Option<&CancellationToken>,
281    ) -> Result<(), String> {
282        debug_assert!(
283            self.eval_cache.active_item_index.is_some(),
284            "evaluate_internal_pre_diffed called without active_item_index — \
285             caller must set up the cache-swap before calling this method"
286        );
287
288        // Always delegate to evaluate_internal so that evaluated_schema is populated correctly
289        // for every item. The previous generation-based skip here left evaluated_schema stale
290        // (with the prior rider's values) when no deps changed — causing get_evaluated_schema_subform
291        // to return wrong values for all but the last-evaluated rider.
292        //
293        // evaluate_internal's all-hit fast path (lines ~314–338) handles the no-change case
294        // efficiently: it writes eval_data + evaluated_schema per formula from T1 cache and
295        // skips the expensive formula engine entirely.
296        self.evaluate_internal(paths, token)
297    }
298
299    /// Internal evaluate that can be called when data is already set
300    /// This avoids double-locking and unnecessary data cloning for re-evaluation from evaluate_dependents
301    pub(crate) fn evaluate_internal(
302        &mut self,
303        paths: Option<&[String]>,
304        token: Option<&CancellationToken>,
305    ) -> Result<(), String> {
306        if let Some(t) = token {
307            if t.is_cancelled() {
308                return Err("Cancelled".to_string());
309            }
310        }
311        time_block!("  evaluate_internal() [total]", {
312            // Acquire lock for synchronous execution
313            let _lock = self.eval_lock.lock().unwrap();
314
315            // Normalize paths to schema pointers for correct filtering
316            let normalized_paths_storage; // Keep alive
317            let normalized_paths = if let Some(p_list) = paths {
318                normalized_paths_storage = p_list
319                    .iter()
320                    .flat_map(|p| {
321                        let normalized = if p.starts_with("#/") {
322                            p.to_string()
323                        } else if p.starts_with('/') {
324                            format!("#{}", p)
325                        } else {
326                            format!("#/{}", p.replace('.', "/"))
327                        };
328                        vec![normalized]
329                    })
330                    .collect::<Vec<_>>();
331                Some(normalized_paths_storage.as_slice())
332            } else {
333                None
334            };
335
336            // Borrow sorted_evaluations via Arc (avoid deep-cloning Vec<Vec<String>>)
337            let eval_batches = self.sorted_evaluations.clone();
338
339            // Track whether any entry was a cache miss (required an actual formula run).
340            // When false (all hits), evaluate_others can skip resolve_layout because no
341            // values changed and the layout state is guaranteed identical.
342            // On the very first evaluation (last_evaluated_generation == u64::MAX), we MUST
343            // force a cache miss so that static schemas (with no formulas) still process
344            // URL templates and layout resolution once.
345            let mut had_cache_miss = self.eval_cache.last_evaluated_generation == u64::MAX;
346
347            // Process each batch - sequentially
348            // Batches are processed sequentially to maintain dependency order
349            // Process value evaluations (simple computed fields with no dependencies)
350            let eval_data_values = self.eval_data.clone();
351            time_block!("      evaluate values", {
352                for eval_key in self.value_evaluations.iter() {
353                    if let Some(t) = token {
354                        if t.is_cancelled() {
355                            return Err("Cancelled".to_string());
356                        }
357                    }
358                    // Skip if has dependencies (handled in sorted batches with correct ordering)
359                    if let Some(deps) = self.dependencies.get(eval_key) {
360                        if !deps.is_empty() {
361                            continue;
362                        }
363                    }
364
365                    // Filter items if paths are provided
366                    if let Some(filter_paths) = normalized_paths {
367                        if !filter_paths.is_empty()
368                            && !filter_paths.iter().any(|p| {
369                                eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())
370                            })
371                        {
372                            continue;
373                        }
374                    }
375
376                    let pointer_path = path_utils::normalize_to_json_pointer(eval_key).into_owned();
377                    let empty_deps = indexmap::IndexSet::new();
378                    let deps = self.dependencies.get(eval_key).unwrap_or(&empty_deps);
379
380                    // Cache hit check
381                    if let Some(_cached_result) = self.eval_cache.check_cache(eval_key, deps) {
382                        continue;
383                    }
384
385                    had_cache_miss = true;
386                    // Cache miss - evaluate
387                    if let Some(logic_id) = self.evaluations.get(eval_key) {
388                        match self.engine.run(logic_id, eval_data_values.data()) {
389                            Ok(val) => {
390                                let cleaned_val = clean_float_noise_scalar(val);
391                                self.eval_cache
392                                    .store_cache(eval_key, deps, cleaned_val.clone());
393
394                                if let Some(pointer_value) =
395                                    self.evaluated_schema.pointer_mut(&pointer_path)
396                                {
397                                    *pointer_value = cleaned_val;
398                                }
399                            }
400                            Err(_) => {
401                                // Formula failed — ensure no raw $evaluation object leaks.
402                                // Write null only if the node still holds the unevaluated formula.
403                                if let Some(node) =
404                                    self.evaluated_schema.pointer_mut(&pointer_path)
405                                {
406                                    if node.is_object()
407                                        && node.get("$evaluation").is_some()
408                                    {
409                                        *node = Value::Null;
410                                    }
411                                }
412                            }
413                        }
414                    }
415                }
416            });
417
418            time_block!("    process batches", {
419                for batch in eval_batches.iter() {
420                    if let Some(t) = token {
421                        if t.is_cancelled() {
422                            return Err("Cancelled".to_string());
423                        }
424                    }
425                    // Skip empty batches
426                    if batch.is_empty() {
427                        continue;
428                    }
429
430                    // Check if we can skip this entire batch optimization
431                    let batch_skipped = time_block!("      batch filter check", {
432                        if let Some(filter_paths) = normalized_paths {
433                            if !filter_paths.is_empty() {
434                                let batch_has_match = batch.iter().any(|eval_key| {
435                                    filter_paths.iter().any(|p| {
436                                        eval_key.starts_with(p.as_str())
437                                            || (p.starts_with(eval_key.as_str())
438                                                && !eval_key.contains("/$params/"))
439                                    })
440                                });
441                                !batch_has_match
442                            } else {
443                                false
444                            }
445                        } else {
446                            false
447                        }
448                    });
449                    if batch_skipped {
450                        continue;
451                    }
452
453                    // Fast path: try to resolve every eval_key in this batch from cache.
454                    // If all hit, skip the expensive exclusive_clone() of the full eval_data tree.
455                    // This is critical for subforms where eval_data contains the full parent payload.
456                    let all_cache_hit = time_block!("      batch cache fast path", {
457                        let mut batch_hits: Vec<(String, Value)> = Vec::with_capacity(batch.len());
458                        let all_hit = batch.iter().all(|eval_key| {
459                            let empty_deps = indexmap::IndexSet::new();
460                            let deps = self.dependencies.get(eval_key).unwrap_or(&empty_deps);
461                            if let Some(cached) = self.eval_cache.check_cache(eval_key, deps) {
462                                let pointer_path =
463                                    path_utils::normalize_to_json_pointer(eval_key).into_owned();
464                                batch_hits.push((pointer_path, cached));
465                                true
466                            } else {
467                                false
468                            }
469                        });
470
471                        if all_hit {
472                            // Populate eval_data AND evaluated_schema so both downstream batches
473                            // and get_evaluated_schema callers see the correct per-item values.
474                            // Previously only eval_data was written here, leaving evaluated_schema
475                            // with stale values from the last full-miss evaluation (e.g. the first
476                            // rider), causing all riders to report the same schema outputs.
477                            for (ptr, val) in batch_hits {
478                                self.eval_data.set(&ptr, val.clone());
479                                if let Some(schema_value) = self.evaluated_schema.pointer_mut(&ptr)
480                                {
481                                    *schema_value = val;
482                                }
483                            }
484                        }
485                        // Partial or full miss — fall through to the normal exclusive_clone path below.
486                        // batch_hits is dropped here; cache lookups will repeat but that's cheap.
487                        all_hit
488                    });
489                    if all_cache_hit {
490                        continue;
491                    }
492                    had_cache_miss = true;
493
494                    // Sequential execution.
495                    // For each formula miss, snapshot_data() gives an O(1) Arc::clone
496                    // as a stable read view. The Arc is dropped before self.eval_data.set()
497                    // so Arc::make_mut always finds rc=1 — zero deep copy, zero latency.
498                    time_block!("      batch sequential eval", {
499                        for eval_key in batch {
500                            if let Some(t) = token {
501                                if t.is_cancelled() {
502                                    return Err("Cancelled".to_string());
503                                }
504                            }
505                            // Filter individual items if paths are provided
506                            if let Some(filter_paths) = normalized_paths {
507                                if !filter_paths.is_empty()
508                                    && !filter_paths.iter().any(|p| {
509                                        eval_key.starts_with(p.as_str())
510                                            || (p.starts_with(eval_key.as_str())
511                                                && !eval_key.contains("/$params/"))
512                                    })
513                                {
514                                    continue;
515                                }
516                            }
517
518                            let pointer_path =
519                                path_utils::normalize_to_json_pointer(eval_key).into_owned();
520
521                            // Cache miss - evaluate
522                            let is_table = self.table_metadata.contains_key(eval_key);
523
524                            if is_table {
525                                time_block!("        table eval", {
526                                    // Snapshot for table read access: Arc::clone is O(1).
527                                    // Scoped so it's dropped before self.eval_data.set() below,
528                                    // keeping self.eval_data.data at rc=1 so Arc::make_mut is free.
529                                    let table_result = {
530                                        let table_scope =
531                                            EvalData::from_arc(self.eval_data.snapshot_data());
532                                        table_evaluate::evaluate_table(
533                                            self,
534                                            eval_key,
535                                            &table_scope,
536                                            token,
537                                        )
538                                        // table_scope dropped here → rc back to 1
539                                    };
540                                    if let Ok((rows, external_deps_opt)) = table_result {
541                                        let result_val = Value::Array(rows);
542                                        if let Some(external_deps) = external_deps_opt {
543                                            self.eval_cache.store_cache(
544                                                eval_key,
545                                                &external_deps,
546                                                result_val.clone(),
547                                            );
548                                        }
549
550                                        // NOTE: bump_params_version / bump_data_version for table results
551                                        // is now handled inside store_cache (conditional on value change).
552                                        // The separate bump here was double-counting: store_cache uses T2
553                                        // comparison while this block used eval_data as reference point,
554                                        // causing two version increments per changed table.
555
556                                        let static_key = format!("/$table{}", pointer_path);
557                                        let arc_value = std::sync::Arc::new(result_val);
558
559                                        Arc::make_mut(&mut self.static_arrays).insert(
560                                            static_key.clone(),
561                                            std::sync::Arc::clone(&arc_value),
562                                        );
563
564                                        self.eval_data.set(&pointer_path, Value::clone(&arc_value));
565
566                                        let marker =
567                                            serde_json::json!({ "$static_array": static_key });
568                                        if let Some(schema_value) =
569                                            self.evaluated_schema.pointer_mut(&pointer_path)
570                                        {
571                                            *schema_value = marker;
572                                        }
573                                    }
574                                });
575                            } else {
576                                let empty_deps = indexmap::IndexSet::new();
577                                let deps = self.dependencies.get(eval_key).unwrap_or(&empty_deps);
578                                let cached_result = self.eval_cache.check_cache(eval_key, &deps);
579
580                                time_block!("        formula eval", {
581                                    if let Some(cached_result) = cached_result {
582                                        // Must still populate eval_data out of cache so subsequent formulas
583                                        // referencing this path in the same iteration can read the exact value
584                                        self.eval_data.set(&pointer_path, cached_result.clone());
585                                        if let Some(schema_value) =
586                                            self.evaluated_schema.pointer_mut(&pointer_path)
587                                        {
588                                            *schema_value = cached_result;
589                                        }
590                                    } else if let Some(logic_id) = self.evaluations.get(eval_key) {
591                                        // snapshot_data() is O(1) Arc::clone — no deep copy.
592                                        // Arc is moved into `snap` and lives only for the
593                                        // engine.run() call, then dropped before set() below.
594                                        // This keeps self.eval_data.data at rc=1 when set()
595                                        // calls Arc::make_mut, so no deep clone ever occurs.
596                                        let val = {
597                                            let snap = self.eval_data.snapshot_data();
598                                            self.engine.run(logic_id, &*snap)
599                                            // snap dropped here → rc back to 1
600                                        };
601                                        match val {
602                                            Ok(val) => {
603                                                let cleaned_val = clean_float_noise_scalar(val);
604                                                let data_path = crate::jsoneval::path_utils::schema_path_to_data_pointer(&pointer_path).into_owned();
605                                                self.eval_cache.store_cache(
606                                                    eval_key,
607                                                    &deps,
608                                                    cleaned_val.clone(),
609                                                );
610
611                                                // Bump data_versions when non-$params field value changes.
612                                                // $params bumps are handled inside store_cache (conditional).
613                                                let old_val = self
614                                                    .eval_data
615                                                    .get(&data_path)
616                                                    .cloned()
617                                                    .unwrap_or(Value::Null);
618                                                if cleaned_val != old_val
619                                                    && !data_path.starts_with("/$params")
620                                                {
621                                                    self.eval_cache.bump_data_version(&data_path);
622                                                }
623
624                                                self.eval_data.set(&pointer_path, cleaned_val.clone());
625                                                if let Some(schema_value) =
626                                                    self.evaluated_schema.pointer_mut(&pointer_path)
627                                                {
628                                                    *schema_value = cleaned_val;
629                                                }
630                                            }
631                                            Err(_) => {
632                                                // Formula failed — ensure no raw $evaluation object leaks.
633                                                // Write null only if the node still holds the unevaluated formula.
634                                                if let Some(node) =
635                                                    self.evaluated_schema.pointer_mut(&pointer_path)
636                                                {
637                                                    if node.is_object()
638                                                        && node.get("$evaluation").is_some()
639                                                    {
640                                                        *node = Value::Null;
641                                                    }
642                                                }
643                                            }
644                                        }
645                                    }
646                                });
647                            }
648                        }
649                    });
650                }
651            });
652
653            // Drop lock before calling evaluate_others
654            drop(_lock);
655
656            // Mark generation stable so the next evaluate_internal call can detect whether
657            // any formula was actually re-stored (via bump_data/params_version) since this run.
658            self.eval_cache.mark_evaluated();
659
660            self.evaluate_others(paths, token, had_cache_miss);
661
662            Ok(())
663        })
664    }
665
666    pub(crate) fn evaluate_others(
667        &mut self,
668        paths: Option<&[String]>,
669        token: Option<&CancellationToken>,
670        had_cache_miss: bool,
671    ) {
672        if let Some(t) = token {
673            if t.is_cancelled() {
674                return;
675            }
676        }
677        time_block!("    evaluate_others()", {
678            // Step 1: Evaluate "rules" and "others" categories with caching
679            // Rules are evaluated here so their values are available in evaluated_schema
680            let combined_count = self.rules_evaluations.len() + self.others_evaluations.len();
681            if combined_count > 0 {
682                time_block!("      evaluate rules+others", {
683                    let eval_data_snapshot = self.eval_data.clone();
684
685                    let normalized_paths: Option<Vec<String>> = paths.map(|p_list| {
686                        p_list
687                            .iter()
688                            .flat_map(|p| {
689                                let ptr = path_utils::dot_notation_to_schema_pointer(p);
690                                // Also support version with /properties/ prefix for root match
691                                let with_props = if ptr.starts_with("#/") {
692                                    format!("#/properties/{}", &ptr[2..])
693                                } else {
694                                    ptr.clone()
695                                };
696                                vec![ptr, with_props]
697                            })
698                            .collect()
699                    });
700
701                    // Sequential evaluation
702                    let combined_evals: Vec<&String> = self
703                        .rules_evaluations
704                        .iter()
705                        .chain(self.others_evaluations.iter())
706                        .collect();
707
708                    for eval_key in combined_evals {
709                        if let Some(t) = token {
710                            if t.is_cancelled() {
711                                return;
712                            }
713                        }
714                        // Filter items if paths are provided
715                        if let Some(filter_paths) = normalized_paths.as_ref() {
716                            if !filter_paths.is_empty()
717                                && !filter_paths.iter().any(|p| {
718                                    eval_key.starts_with(p.as_str())
719                                        || (p.starts_with(eval_key.as_str())
720                                            && !eval_key.contains("/$params/"))
721                                })
722                            {
723                                continue;
724                            }
725                        }
726
727                        let pointer_path =
728                            path_utils::normalize_to_json_pointer(eval_key).into_owned();
729                        let empty_deps = indexmap::IndexSet::new();
730                        let deps = self.dependencies.get(eval_key).unwrap_or(&empty_deps);
731
732                        if let Some(cached_result) = self.eval_cache.check_cache(eval_key, &deps) {
733                            if let Some(pointer_value) =
734                                self.evaluated_schema.pointer_mut(&pointer_path)
735                            {
736                                if !pointer_path.starts_with("$")
737                                    && pointer_path.contains("/rules/")
738                                    && !pointer_path.ends_with("/value")
739                                {
740                                    if let Some(pointer_obj) = pointer_value.as_object_mut() {
741                                        pointer_obj.remove("$evaluation");
742                                        pointer_obj
743                                            .insert("value".to_string(), cached_result.clone());
744                                    }
745                                } else {
746                                    *pointer_value = cached_result.clone();
747                                }
748                            }
749                            continue;
750                        }
751                        if let Some(logic_id) = self.evaluations.get(eval_key) {
752                            match self.engine.run(logic_id, eval_data_snapshot.data()) {
753                                Ok(val) => {
754                                    let cleaned_val = clean_float_noise_scalar(val);
755                                    self.eval_cache
756                                        .store_cache(eval_key, &deps, cleaned_val.clone());
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        // Step 2: Evaluate options URL templates (handles {variable} patterns)
797        // Skip when all entries were cache hits — template inputs can't have changed.
798        if had_cache_miss {
799            time_block!("      evaluate_options_templates", {
800                self.evaluate_options_templates(paths);
801            });
802
803            // Step 3: Resolve layout logic (metadata injection, hidden propagation)
804            // Skip when no values changed — layout state is guaranteed identical.
805            time_block!("      resolve_layout", {
806                let _ = self.resolve_layout(false);
807            });
808        }
809    }
810
811    /// Evaluate options URL templates (handles {variable} patterns)
812    fn evaluate_options_templates(&mut self, paths: Option<&[String]>) {
813        // Use pre-collected options templates from parsing (Arc clone is cheap)
814        let templates_to_eval = self.options_templates.clone();
815
816        // Evaluate each template
817        for (path, template_str, params_path) in templates_to_eval.iter() {
818            // Filter items if paths are provided
819            // 'path' here is the schema path to the field (dot notation or similar, need to check)
820            // It seems to be schema pointer based on usage in other methods
821            if let Some(filter_paths) = paths {
822                if !filter_paths.is_empty()
823                    && !filter_paths
824                        .iter()
825                        .any(|p| path.starts_with(p.as_str()) || p.starts_with(path.as_str()))
826                {
827                    continue;
828                }
829            }
830
831            if let Some(params) = self.evaluated_schema.pointer(&params_path) {
832                if let Ok(evaluated) = self.evaluate_template(&template_str, params) {
833                    if let Some(target) = self.evaluated_schema.pointer_mut(&path) {
834                        *target = Value::String(evaluated);
835                    }
836                }
837            }
838        }
839    }
840
841    /// Evaluate a template string like "api/users/{id}" with params
842    fn evaluate_template(&self, template: &str, params: &Value) -> Result<String, String> {
843        let mut result = template.to_string();
844
845        // Simple template evaluation: replace {key} with params.key
846        if let Value::Object(params_map) = params {
847            for (key, value) in params_map {
848                let placeholder = format!("{{{}}}", key);
849                if let Some(str_val) = value.as_str() {
850                    result = result.replace(&placeholder, str_val);
851                } else {
852                    // Convert non-string values to strings
853                    result = result.replace(&placeholder, &value.to_string());
854                }
855            }
856        }
857
858        Ok(result)
859    }
860}