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