json-eval-rs 0.0.87

High-performance JSON Logic evaluator with schema validation and dependency tracking. Built on blazing-fast Rust engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
// Subform methods for isolated array field evaluation

use crate::jsoneval::cancellation::CancellationToken;
use crate::jsoneval::eval_data::EvalData;
use crate::JSONEval;
use crate::ReturnFormat;
use serde_json::Value;

/// Decomposes a subform path that may optionally include a trailing item index,
/// and normalizes the base portion to the canonical schema-pointer key used in the
/// subform registry (e.g. `"#/illustration/properties/product_benefit/properties/riders"`).
///
/// Accepted formats for the **base** portion:
/// - Schema pointer:    `"#/illustration/properties/product_benefit/properties/riders"`
/// - Raw JSON pointer:  `"/illustration/properties/product_benefit/properties/riders"`
/// - Dot notation:      `"illustration.product_benefit.riders"`
///
/// Accepted formats for the **index** suffix (stripped before lookup):
/// - Trailing dot-index:     `"…riders.1"`
/// - Trailing slash-index:   `"…riders/1"`
/// - Bracket array index:    `"…riders[1]"` or `"…riders[1]."`
///
/// Returns `(canonical_base_path, optional_index)`.
fn resolve_subform_path(path: &str) -> (String, Option<usize>) {
    // --- Step 1: strip a trailing bracket array index, e.g. "riders[2]" or "riders[2]."
    let path = path.trim_end_matches('.');
    let (path, bracket_idx) = if let Some(bracket_start) = path.rfind('[') {
        let after = &path[bracket_start + 1..];
        if let Some(bracket_end) = after.find(']') {
            let idx_str = &after[..bracket_end];
            if let Ok(idx) = idx_str.parse::<usize>() {
                // strip everything from '[' onward (including any trailing '.')
                let base = path[..bracket_start].trim_end_matches('.');
                (base, Some(idx))
            } else {
                (path, None)
            }
        } else {
            (path, None)
        }
    } else {
        (path, None)
    };

    // --- Step 2: strip a trailing numeric segment (dot or slash separated)
    let (base_raw, trailing_idx) = if bracket_idx.is_none() {
        // Check dot-notation trailing index: "foo.bar.2"
        if let Some(dot_pos) = path.rfind('.') {
            let suffix = &path[dot_pos + 1..];
            if let Ok(idx) = suffix.parse::<usize>() {
                (&path[..dot_pos], Some(idx))
            } else {
                (path, None)
            }
        }
        // Check JSON-pointer trailing index: "#/foo/bar/0" or "/foo/bar/0"
        else if let Some(slash_pos) = path.rfind('/') {
            let suffix = &path[slash_pos + 1..];
            if let Ok(idx) = suffix.parse::<usize>() {
                (&path[..slash_pos], Some(idx))
            } else {
                (path, None)
            }
        } else {
            (path, None)
        }
    } else {
        (path, None)
    };

    let final_idx = bracket_idx.or(trailing_idx);

    // --- Step 3: normalize base_raw to a canonical schema pointer
    let canonical = normalize_to_subform_key(base_raw);

    (canonical, final_idx)
}

/// Normalize any path format to the canonical subform registry key.
///
/// The registry stores keys as `"#/field/properties/subfield/properties/…"` — exactly
/// as produced by the schema `walk()` function. This function converts all supported
/// formats into that form.
fn normalize_to_subform_key(path: &str) -> String {
    // Already a schema pointer — return as-is
    if path.starts_with("#/") {
        return path.to_string();
    }

    // Raw JSON pointer "/foo/properties/bar" → prefix with '#'
    if path.starts_with('/') {
        return format!("#{}", path);
    }

    // Dot-notation: "illustration.product_benefit.riders"
    // → "#/illustration/properties/product_benefit/properties/riders"
    crate::jsoneval::path_utils::dot_notation_to_schema_pointer(path)
}

impl JSONEval {
    /// Resolves the subform path, allowing aliases like "riders" to match the full
    /// schema pointer "#/illustration/properties/product_benefit/properties/riders".
    /// This ensures alias paths and full paths share the same underlying subform store and cache.
    pub(crate) fn resolve_subform_path_alias(&self, path: &str) -> (String, Option<usize>) {
        let (mut canonical, idx) = resolve_subform_path(path);

        if !self.subforms.contains_key(&canonical) {
            let search_suffix = if canonical.starts_with("#/") {
                format!("/properties/{}", &canonical[2..])
            } else {
                format!("/properties/{}", canonical)
            };

            for k in self.subforms.keys() {
                if k.ends_with(&search_suffix) || k == &canonical {
                    canonical = k.to_string();
                    break;
                }
            }
        }

        (canonical, idx)
    }

    /// Execute `f` on the subform at `base_path[idx]` with the parent cache swapped in.
    ///
    /// Lifecycle:
    /// 1. Set `data_value` + `context_value` on the subform's `eval_data`.
    /// 2. Compute item-level diff for `field_key` → bump `subform_caches[idx].data_versions`.
    /// 3. `mem::take` parent cache → set `active_item_index = Some(idx)` → swap into subform.
    /// 4. Execute `f(subform)` → collect result.
    /// 5. Swap parent cache back out → restore `self.eval_cache`.
    ///
    /// This ensures all three operations (evaluate / validate / evaluate_dependents)
    /// share parent-form Tier-2 cache entries, without duplicating the swap boilerplate.
    fn with_item_cache_swap<F, T>(
        &mut self,
        base_path: &str,
        idx: usize,
        data_value: Value,
        context_value: Value,
        f: F,
    ) -> Result<T, String>
    where
        F: FnOnce(&mut JSONEval) -> Result<T, String>,
    {
        let field_key = base_path
            .split('/')
            .next_back()
            .unwrap_or(base_path)
            .to_string();

        // Step 1: update subform data and extract item snapshot for targeted diff.
        // Scoped block releases the mutable borrow on `self.subforms` before we touch
        // `self.eval_cache` (they are disjoint fields, but keep it explicit).
        let (old_item_snapshot, new_item_val, subform_item_cache_opt, array_path, item_path) = {
            let subform = self
                .subforms
                .get_mut(base_path)
                .ok_or_else(|| format!("Subform not found: {}", base_path))?;

            let old_item_snapshot = subform
                .eval_cache
                .subform_caches
                .get(&idx)
                .map(|c| c.item_snapshot.clone())
                .unwrap_or(Value::Null);

            subform
                .eval_data
                .replace_data_and_context(data_value, context_value);
            let new_item_val = subform
                .eval_data
                .data()
                .get(&field_key)
                .cloned()
                .unwrap_or(Value::Null);

            // INJECT the item into the parent array location within subform's eval_data!
            // The frontend sometimes only provides the active item root but leaves the
            // corresponding slot empty or stale in the parent array tree of the wrapper.
            // Formulas that aggregate over the parent array must see the active item.
            let array_path = crate::jsoneval::path_utils::schema_path_to_data_pointer(base_path).into_owned();
            let item_path = format!("{}/{}", array_path, idx);
            subform.eval_data.set(&item_path, new_item_val.clone());

            // Pull out any existing item-scoped entries from the subform's own cache
            // so they can be merged into the parent cache below.
            let existing = subform.eval_cache.subform_caches.remove(&idx);
            (
                old_item_snapshot,
                new_item_val,
                existing,
                array_path,
                item_path,
            )
        }; // subform borrow released here

        // Unified store fallback: if the subform's own per-item cache has no snapshot for this
        // index (e.g. this is the first evaluate_subform call after a full evaluate()), treat the
        // parent's eval_data slot as the canonical baseline. The parent always holds the most
        // recent array data written by evaluate() or evaluate_dependents(), so using it avoids
        // treating an already-evaluated item as brand-new and forcing full table re-evaluation.
        let parent_item = self.eval_data.get(&item_path).cloned();
        let old_item_snapshot = if old_item_snapshot == Value::Null {
            parent_item.clone().unwrap_or(Value::Null)
        } else {
            old_item_snapshot
        };

        // An item is "new" only when the parent's eval_data has no entry at the item path.
        // Using the subform's own snapshot cache as the authority (old_item_snapshot == Null)
        // is not correct after Step 6 persistence re-seeds the cache: a rider that was
        // previously evaluate_subform'd would have a snapshot but may still be absent from
        // the parent array (e.g. new rider scenario after evaluate_dependents_subform).
        let is_new_item = parent_item.is_none();

        let mut parent_cache = std::mem::take(&mut self.eval_cache);
        parent_cache.ensure_active_item_cache(idx);

        // Snapshot item versions BEFORE the diff so we can detect only NEW bumps below.
        // `any_bumped_with_prefix(v > 0)` would return true for historical bumps from prior
        // calls, causing invalidate_params_tables_for_item to fire on every evaluate_subform
        // even when no rider data actually changed.
        let pre_diff_item_versions = parent_cache
            .subform_caches
            .get(&idx)
            .map(|c| c.data_versions.clone());

        if let Some(c) = parent_cache.subform_caches.get_mut(&idx) {
            // Only inherit $params-scoped versions from the parent so that data-path
            // bumps from other items or previous calls don't contaminate this item's baseline.
            c.data_versions
                .merge_from_params(&parent_cache.params_versions);
            // Diff only the item field to find what changed (skips the 5 MB parent tree).
            crate::jsoneval::eval_cache::diff_and_update_versions(
                &mut c.data_versions,
                &format!("/{}", field_key),
                &old_item_snapshot,
                &new_item_val,
                "with_item_cache_swap_diff_and_update_versions"
            );
            c.item_snapshot = new_item_val.clone();
        }

        // Propagate paths NEWLY bumped by this diff into parent_cache.data_versions so that
        // check_table_cache (which validates T2 global entries against self.data_versions only)
        // correctly detects changes to rider fields like `sa`, `code`, etc.
        //
        // Without this, a field changed via evaluate_dependents_subform (e.g. sa: 0 → 200M)
        // only bumps the per-item tracker. The T2 entry for RIDER_ZLOB_TABLE (cached with sa=0)
        // still looks valid when validated against self.data_versions → stale rows → first_prem=0.
        //
        // We use pre_diff_item_versions as the baseline so only NEW bumps from THIS diff pass
        // are propagated, NOT historical bumps accumulated by prior evaluate_subform calls.
        // This prevents the regression where run_subform_pass sees stale per-rider bumps
        // and erroneously re-evaluates expensive tables (RIDER_ZLOB_TABLE etc.) for every rider.
        {
            let item_field_prefix = format!("/{}/", field_key);
            if let (Some(ref pre), Some(c)) = (
                &pre_diff_item_versions,
                parent_cache.subform_caches.get(&idx),
            ) {
                let newly_bumped: Vec<String> = c
                    .data_versions
                    .versions()
                    .filter(|(k, &v)| k.starts_with(&item_field_prefix) && v > pre.get(k))
                    .map(|(k, _)| k.to_string())
                    .collect();
                if !newly_bumped.is_empty() {
                    for k in newly_bumped {
                        parent_cache.data_versions.bump(&k, "propagate_newly_bumped");
                    }
                    parent_cache.eval_generation += 1;
                }
            }
        }

        parent_cache.active_item_index = Some(idx);

        // Restore cached entries that lived in the subform's own per-item cache.
        // Only restore entries whose dependency versions still match the current item
        // data_versions: if a field changed (e.g. sa bumped), entries that depended on
        // that field are stale and must not be re-inserted (they would cause false T1 hits).
        if let Some(subform_item_cache) = subform_item_cache_opt {
            if let Some(c) = parent_cache.subform_caches.get_mut(&idx) {
                // Merge historical data_versions from the prior subform item cache BEFORE
                // computing current_dv. The fresh item cache (ensure_active_item_cache) only
                // has paths bumped by the current diff. Historical bumps (e.g. /riders/sa=1
                // from prior calls) live in subform_item_cache.data_versions. Without this
                // merge, current_dv["/riders/sa"]=0 while T1 entries store dep_ver=1, so all
                // T1 entries are evicted and every table falls through to the T2 path.
                // After the merge, current_dv reflects the full accumulated state; the diff
                // above already bumped any newly-changed fields further, so stale entries that
                // depended on those fields are still correctly evicted.
                c.data_versions
                    .merge_from(&subform_item_cache.data_versions);

                let current_dv = c.data_versions.clone();
                for (k, v) in subform_item_cache.entries {
                    // Skip if entry already exists (parent-form run may have added a fresher result).
                    if c.entries.contains_key(&k) {
                        continue;
                    }
                    // Validate all dep versions against the current item data_versions.
                    let still_valid = v.dep_versions.iter().all(|(dep_path, &cached_ver)| {
                        let current_ver = if dep_path.starts_with("/$params") {
                            parent_cache.params_versions.get(dep_path)
                        } else {
                            current_dv.get(dep_path)
                        };
                        current_ver == cached_ver
                    });
                    if still_valid {
                        c.entries.insert(k, v);
                    }
                }
            }
        }

        // Insert into the parent eval_data as well (to make the item visible to global formulas on main evaluate).
        // Only write (and bump version) when the value actually changed: prevents spurious riders-array
        // version increments on repeated evaluate_subform calls where the rider data is unchanged.
        let current_at_item_path = self.eval_data.get(&item_path).cloned();
        if current_at_item_path.as_ref() != Some(&new_item_val) {
            self.eval_data.set(&item_path, new_item_val.clone());
            if is_new_item {
                parent_cache.bump_data_version(&array_path);
            }
        }

        // Re-evaluate `$params` tables that depend on subform item paths that changed.
        // This is required not just for brand-new items, but also whenever a tracked field
        // (like `riders.sa`) changes value: tables like RIDER_ZLOB_TABLE depend on rider.sa
        // and must produce updated rows that reflect the new sa before the subform's own
        // formula evaluation runs (otherwise cached old rows are reused).
        //
        // Gate: only re-evaluate tables when at least one item-level path was NEWLY bumped
        // in this diff pass. Using any_bumped_with_prefix(v > 0) would return true for
        // historical bumps from prior calls, causing spurious table invalidation every time.
        let field_prefix = format!("/{}/", field_key);
        let item_paths_bumped = match &pre_diff_item_versions {
            None => {
                // No pre-diff snapshot = cache slot was just created, treat as new
                parent_cache
                    .subform_caches
                    .get(&idx)
                    .map(|c| c.data_versions.any_bumped_with_prefix(&field_prefix))
                    .unwrap_or(false)
            }
            Some(pre) => {
                // Only count bumps that occurred during this specific diff pass
                parent_cache
                    .subform_caches
                    .get(&idx)
                    .map(|c| {
                        c.data_versions
                            .any_newly_bumped_with_prefix(&field_prefix, pre)
                    })
                    .unwrap_or(false)
            }
        };

        if is_new_item || item_paths_bumped {
            // Collect which rider data paths were NEWLY bumped in this diff pass.
            // When item_paths_bumped = true, the diff detected changes — but we only want to
            // invalidate tables that ACTUALLY depend on those changed paths. Tables like
            // ILST_TABLE / RIDER_ZLOB_TABLE don't depend on computed outputs (wop_rider_premi,
            // first_prem), so bumping them forces unnecessary re-evaluation and increments
            // eval_generation, preventing the generation-based skip in evaluate_internal_pre_diffed.
            let newly_bumped_paths: Option<Vec<String>> = if item_paths_bumped {
                let paths = pre_diff_item_versions.as_ref().and_then(|pre| {
                    parent_cache.subform_caches.get(&idx).map(|c| {
                        c.data_versions
                            .versions()
                            .filter(|(k, &v)| k.starts_with(&field_prefix) && v > pre.get(k))
                            .map(|(k, _)| {
                                // Convert data-version path (e.g. /riders/wop_rider_premi) to schema dep
                                // format (e.g. #/riders/properties/wop_rider_premi) for dep matching.
                                let sub = k.trim_start_matches(&field_prefix);
                                format!("#/{}/properties/{}", field_key, sub)
                            })
                            .collect::<Vec<_>>()
                    })
                });
                paths
            } else {
                None
            };

            let params_table_keys: Vec<String> = self
                .table_metadata
                .keys()
                .filter(|k| k.starts_with("#/$params"))
                .filter(|k| {
                    if is_new_item {
                        return true; // new rider: invalidate all tables
                    }
                    // Only invalidate tables whose declared deps overlap the changed paths.
                    // If newly_bumped_paths is None (shouldn't happen when item_paths_bumped=true),
                    // fall back to invalidating all.
                    let Some(ref bumped) = newly_bumped_paths else {
                        return true;
                    };
                    if bumped.is_empty() {
                        return false;
                    }
                    self.dependencies
                        .get(*k)
                        .map(|deps| {
                            deps.iter().any(|dep| {
                                bumped
                                    .iter()
                                    .any(|b| dep == b || dep.starts_with(b.as_str()))
                            })
                        })
                        .unwrap_or(false)
                })
                .cloned()
                .collect();
            if !params_table_keys.is_empty() {
                parent_cache.invalidate_params_tables_for_item(idx, &params_table_keys);

                let eval_data_snapshot = self.eval_data.snapshot_data();
                for key in &params_table_keys {
                    // CRITICAL FIX: Only evaluate global tables on the parent if they do NOT
                    // depend on subform-specific item paths (like `#/riders/...`).
                    // Tables like WOP_ZLOB_PREMI_TABLE contain formulas like `#/riders/properties/code`
                    // and MUST be evaluated by the subform engine to see the subform's current data.
                    // Tables like WOP_RIDERS contain formulas like `#/illustration/product_benefit/riders`
                    // and MUST be evaluated by the parent engine to see the full parent array.
                    let depends_on_subform_item = if let Some(deps) = self.dependencies.get(key) {
                        let subform_dep_prefix = format!("#/{}/properties/", field_key);
                        let subform_dep_prefix_short = format!("#/{}/", field_key);
                        deps.iter().any(|dep| {
                            dep.starts_with(&subform_dep_prefix)
                                || dep.starts_with(&subform_dep_prefix_short)
                        })
                    } else {
                        false
                    };

                    if depends_on_subform_item {
                        continue;
                    }

                    // Evaluate the table using parent's updated data
                    if let Ok((rows, external_deps_opt)) =
                        crate::jsoneval::table_evaluate::evaluate_table(
                            self,
                            key,
                            &EvalData::from_arc(std::sync::Arc::clone(&eval_data_snapshot)),
                            None,
                        )
                    {
                        if crate::utils::is_debug_cache_enabled() {
                            println!("PARENT EVALUATED TABLE {} -> {} rows", key, rows.len());
                        }
                        let result_val = serde_json::Value::Array(rows);

                        if let Some(external_deps) = external_deps_opt {
                            // We must temporarily clear active_item_index so store_cache puts this in T2 (global)
                            // Then the subform can hit it via T2 fallback check.
                            parent_cache.active_item_index = None;
                            parent_cache.store_cache(key, &external_deps, result_val);
                            parent_cache.active_item_index = Some(idx);
                        }
                    } else {
                        if crate::utils::is_debug_cache_enabled() {
                            println!("PARENT EVALUATED TABLE {} -> ERROR", key);
                        }
                    }
                }
            }
        }

        // Step 3: swap parent cache into subform so Tier 1 + Tier 2 entries are visible.
        {
            let subform = self.subforms.get_mut(base_path).unwrap();
            std::mem::swap(&mut subform.eval_cache, &mut parent_cache);
        }

        // Step 4: run the caller-supplied operation.
        let result = {
            let subform = self.subforms.get_mut(base_path).unwrap();
            f(subform)
        };

        // Step 5: restore parent cache.
        {
            let subform = self.subforms.get_mut(base_path).unwrap();
            std::mem::swap(&mut subform.eval_cache, &mut parent_cache);
        }
        parent_cache.active_item_index = None;
        self.eval_cache = parent_cache;

        // Step 6: persist the updated T1 item cache (snapshot + entries) back into the subform's
        // own per-item cache. Without this, the next evaluate_subform call for the same idx reads
        // old_item_snapshot = Null from the subform cache (it was removed at line 183) and treats
        // the rider as brand-new, forcing a full re-diff and invalidating all T1 entries.
        // Also store the subform's evaluated_schema snapshot (written by evaluate_internal above)
        // so get_evaluated_schema_subform can return per-item values with an O(1) cache read.
        {
            let subform = self.subforms.get_mut(base_path).unwrap();
            if let Some(item_cache) = self.eval_cache.subform_caches.get_mut(&idx) {
                item_cache.evaluated_schema = Some(subform.evaluated_schema.clone());
                subform
                    .eval_cache
                    .subform_caches
                    .insert(idx, item_cache.clone());
            }
        }

        result
    }

    /// Evaluate a subform identified by `subform_path`.
    ///
    /// The path may include a trailing item index to bind the evaluation to a specific
    /// array element and enable the two-tier cache-swap strategy automatically:
    ///
    /// ```text
    /// // Evaluate riders item 1 with index-aware cache
    /// eval.evaluate_subform("illustration.product_benefit.riders.1", data, ctx, None, None)?;
    /// ```
    ///
    /// Without a trailing index, the subform is evaluated in isolation (no cache swap).
    pub fn evaluate_subform(
        &mut self,
        subform_path: &str,
        data: &str,
        context: Option<&str>,
        paths: Option<&[String]>,
        token: Option<&CancellationToken>,
    ) -> Result<(), String> {
        let (base_path, idx_opt) = self.resolve_subform_path_alias(subform_path);
        if let Some(idx) = idx_opt {
            self.evaluate_subform_item(&base_path, idx, data, context, paths, token)
        } else {
            let subform = self
                .subforms
                .get_mut(base_path.as_ref() as &str)
                .ok_or_else(|| format!("Subform not found: {}", base_path))?;
            subform.evaluate(data, context, paths, token)
        }
    }

    /// Internal: evaluate a single subform item at `idx` using the cache-swap strategy.
    fn evaluate_subform_item(
        &mut self,
        base_path: &str,
        idx: usize,
        data: &str,
        context: Option<&str>,
        paths: Option<&[String]>,
        token: Option<&CancellationToken>,
    ) -> Result<(), String> {
        let data_value = crate::jsoneval::json_parser::parse_json_str(data)
            .map_err(|e| format!("Failed to parse subform data: {}", e))?;
        let context_value = if let Some(ctx) = context {
            crate::jsoneval::json_parser::parse_json_str(ctx)
                .map_err(|e| format!("Failed to parse subform context: {}", e))?
        } else {
            Value::Object(serde_json::Map::new())
        };

        self.with_item_cache_swap(base_path, idx, data_value, context_value, |sf| {
            sf.evaluate_internal_pre_diffed(paths, token)
        })
    }

    /// Validate subform data against its schema rules.
    ///
    /// Supports the same trailing-index path syntax as `evaluate_subform`. When an index
    /// is present the parent cache is swapped in first, ensuring rule evaluations that
    /// depend on `$params` tables share already-computed parent-form results.
    pub fn validate_subform(
        &mut self,
        subform_path: &str,
        data: &str,
        context: Option<&str>,
        paths: Option<&[String]>,
        token: Option<&CancellationToken>,
    ) -> Result<crate::ValidationResult, String> {
        let (base_path, idx_opt) = self.resolve_subform_path_alias(subform_path);
        if let Some(idx) = idx_opt {
            let data_value = crate::jsoneval::json_parser::parse_json_str(data)
                .map_err(|e| format!("Failed to parse subform data: {}", e))?;
            let context_value = if let Some(ctx) = context {
                crate::jsoneval::json_parser::parse_json_str(ctx)
                    .map_err(|e| format!("Failed to parse subform context: {}", e))?
            } else {
                Value::Object(serde_json::Map::new())
            };
            let data_for_validation = data_value.clone();
            self.with_item_cache_swap(
                base_path.as_ref(),
                idx,
                data_value,
                context_value,
                move |sf| {
                    // Warm the evaluation cache before running rule checks.
                    sf.evaluate_internal_pre_diffed(paths, token)?;
                    sf.validate_pre_set(data_for_validation, paths, token)
                },
            )
        } else {
            let subform = self
                .subforms
                .get_mut(base_path.as_ref() as &str)
                .ok_or_else(|| format!("Subform not found: {}", base_path))?;
            subform.validate(data, context, paths, token)
        }
    }

    /// Evaluate dependents in a subform when a field changes.
    ///
    /// Supports the same trailing-index path syntax as `evaluate_subform`. When an index
    /// is present the parent cache is swapped in, so dependent evaluation runs with
    /// Tier-2 entries visible and item-scoped version bumps propagate to `eval_generation`.
    pub fn evaluate_dependents_subform(
        &mut self,
        subform_path: &str,
        changed_paths: &[String],
        data: Option<&str>,
        context: Option<&str>,
        re_evaluate: bool,
        token: Option<&CancellationToken>,
        canceled_paths: Option<&mut Vec<String>>,
        include_subforms: bool,
    ) -> Result<Value, String> {
        let (base_path, idx_opt) = self.resolve_subform_path_alias(subform_path);
        if let Some(idx) = idx_opt {
            // Parse or snapshot data for the swap / diff computation.
            let (data_value, context_value) = if let Some(data_str) = data {
                let dv = crate::jsoneval::json_parser::parse_json_str(data_str)
                    .map_err(|e| format!("Failed to parse subform data: {}", e))?;
                let cv = if let Some(ctx) = context {
                    crate::jsoneval::json_parser::parse_json_str(ctx)
                        .map_err(|e| format!("Failed to parse subform context: {}", e))?
                } else {
                    Value::Object(serde_json::Map::new())
                };
                (dv, cv)
            } else {
                // No new data provided — snapshot current subform state so diff is a no-op.
                let subform = self
                    .subforms
                    .get(base_path.as_ref() as &str)
                    .ok_or_else(|| format!("Subform not found: {}", base_path))?;
                let dv = subform.eval_data.snapshot_data_clone();
                (dv, Value::Object(serde_json::Map::new()))
            };
            self.with_item_cache_swap(base_path.as_ref(), idx, data_value, context_value, |sf| {
                // Data is already set by with_item_cache_swap; pass None to avoid re-parsing.
                sf.evaluate_dependents(
                    changed_paths,
                    None,
                    None,
                    re_evaluate,
                    token,
                    None,
                    include_subforms,
                )
            })
        } else {
            let subform = self
                .subforms
                .get_mut(base_path.as_ref() as &str)
                .ok_or_else(|| format!("Subform not found: {}", base_path))?;
            subform.evaluate_dependents(
                changed_paths,
                data,
                context,
                re_evaluate,
                token,
                canceled_paths,
                include_subforms,
            )
        }
    }

    /// Resolve layout for subform.
    pub fn resolve_layout_subform(
        &mut self,
        subform_path: &str,
        evaluate: bool,
    ) -> Result<(), String> {
        let (base_path, _) = self.resolve_subform_path_alias(subform_path);
        let subform = self
            .subforms
            .get_mut(base_path.as_ref() as &str)
            .ok_or_else(|| format!("Subform not found: {}", base_path))?;
        let _ = subform.resolve_layout(evaluate);
        Ok(())
    }

    /// Get evaluated schema from subform.
    pub fn get_evaluated_schema_subform(
        &mut self,
        subform_path: &str,
        resolve_layout: bool,
    ) -> Value {
        let (base_path, idx_opt) = self.resolve_subform_path_alias(subform_path);

        if let Some(idx) = idx_opt {
            // Read the per-item evaluated_schema snapshot stored by the most recent
            // evaluate_subform_item call for this index (Step 6 in with_item_cache_swap).
            //
            // This is the correct approach: the subform's evaluated_schema is a single
            // shared object that is overwritten by every evaluate_subform call. Trying to
            // re-run evaluate_internal in a shared context is fragile and ordering-dependent.
            // Instead, we capture the schema snapshot immediately after each item evaluates
            // and store it in SubformItemCache.evaluated_schema for O(1) retrieval here.
            if let Some(schema) = self
                .eval_cache
                .subform_caches
                .get(&idx)
                .and_then(|c| c.evaluated_schema.clone())
            {
                return schema;
            }
            // Fallback: no snapshot yet — run the evaluation now.
            if let Some(subform) = self.subforms.get_mut(base_path.as_ref() as &str) {
                subform.get_evaluated_schema(resolve_layout)
            } else {
                Value::Null
            }
        } else if let Some(subform) = self.subforms.get_mut(base_path.as_ref() as &str) {
            subform.get_evaluated_schema(resolve_layout)
        } else {
            Value::Null
        }
    }

    /// Get schema value from subform in nested object format (all .value fields).
    pub fn get_schema_value_subform(&mut self, subform_path: &str) -> Value {
        let (base_path, _) = self.resolve_subform_path_alias(subform_path);
        if let Some(subform) = self.subforms.get_mut(base_path.as_ref() as &str) {
            subform.get_schema_value()
        } else {
            Value::Null
        }
    }

    /// Get schema values from subform as a flat array of path-value pairs.
    pub fn get_schema_value_array_subform(&self, subform_path: &str) -> Value {
        let (base_path, _) = self.resolve_subform_path_alias(subform_path);
        if let Some(subform) = self.subforms.get(base_path.as_ref() as &str) {
            subform.get_schema_value_array()
        } else {
            Value::Array(vec![])
        }
    }

    /// Get schema values from subform as a flat object with dotted path keys.
    pub fn get_schema_value_object_subform(&self, subform_path: &str) -> Value {
        let (base_path, _) = self.resolve_subform_path_alias(subform_path);
        if let Some(subform) = self.subforms.get(base_path.as_ref() as &str) {
            subform.get_schema_value_object()
        } else {
            Value::Object(serde_json::Map::new())
        }
    }

    /// Get evaluated schema without $params from subform.
    pub fn get_evaluated_schema_without_params_subform(
        &mut self,
        subform_path: &str,
        resolve_layout: bool,
    ) -> Value {
        let (base_path, _) = self.resolve_subform_path_alias(subform_path);
        if let Some(subform) = self.subforms.get_mut(base_path.as_ref() as &str) {
            subform.get_evaluated_schema_without_params(resolve_layout)
        } else {
            Value::Null
        }
    }

    /// Get evaluated schema by specific path from subform.
    pub fn get_evaluated_schema_by_path_subform(
        &mut self,
        subform_path: &str,
        schema_path: &str,
        skip_layout: bool,
    ) -> Option<Value> {
        let (base_path, _) = self.resolve_subform_path_alias(subform_path);
        self.subforms.get_mut(base_path.as_ref() as &str).map(|sf| {
            sf.get_evaluated_schema_by_paths(
                &[schema_path.to_string()],
                skip_layout,
                Some(ReturnFormat::Nested),
            )
        })
    }

    /// Get evaluated schema by multiple paths from subform.
    pub fn get_evaluated_schema_by_paths_subform(
        &mut self,
        subform_path: &str,
        schema_paths: &[String],
        skip_layout: bool,
        format: Option<crate::ReturnFormat>,
    ) -> Value {
        let (base_path, _) = self.resolve_subform_path_alias(subform_path);
        if let Some(subform) = self.subforms.get_mut(base_path.as_ref() as &str) {
            subform.get_evaluated_schema_by_paths(
                schema_paths,
                skip_layout,
                Some(format.unwrap_or(ReturnFormat::Flat)),
            )
        } else {
            match format.unwrap_or_default() {
                crate::ReturnFormat::Array => Value::Array(vec![]),
                _ => Value::Object(serde_json::Map::new()),
            }
        }
    }

    /// Get schema by specific path from subform.
    pub fn get_schema_by_path_subform(
        &self,
        subform_path: &str,
        schema_path: &str,
    ) -> Option<Value> {
        let (base_path, _) = self.resolve_subform_path_alias(subform_path);
        self.subforms
            .get(base_path.as_ref() as &str)
            .and_then(|sf| sf.get_schema_by_path(schema_path))
    }

    /// Get schema by multiple paths from subform.
    pub fn get_schema_by_paths_subform(
        &self,
        subform_path: &str,
        schema_paths: &[String],
        format: Option<crate::ReturnFormat>,
    ) -> Value {
        let (base_path, _) = self.resolve_subform_path_alias(subform_path);
        if let Some(subform) = self.subforms.get(base_path.as_ref() as &str) {
            subform.get_schema_by_paths(schema_paths, Some(format.unwrap_or(ReturnFormat::Flat)))
        } else {
            match format.unwrap_or_default() {
                crate::ReturnFormat::Array => Value::Array(vec![]),
                _ => Value::Object(serde_json::Map::new()),
            }
        }
    }

    /// Get list of available subform paths.
    pub fn get_subform_paths(&self) -> Vec<String> {
        self.subforms.keys().cloned().collect()
    }

    /// Check if a subform exists at the given path.
    pub fn has_subform(&self, subform_path: &str) -> bool {
        let (base_path, _) = self.resolve_subform_path_alias(subform_path);
        self.subforms.contains_key(base_path.as_ref() as &str)
    }
}