rototo 0.1.0-alpha.8

Control plane for runtime configuration of your application.
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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
use std::collections::{BTreeMap, BTreeSet};
use std::net::IpAddr;
use std::sync::Arc;

use cel::common::ast::{EntryExpr, Expr, LiteralValue, operators};
use cel::{Context as CelContext, ExecutionError, IdedExpr, Value as CelValue};
use glob::Pattern;
use regex::Regex;
use semver::{Version, VersionReq};
use serde_json::{Number, Value as JsonValue};

use crate::error::{Result, RototoError};
use crate::predicate::{CidrBlock, parse_rfc3339_timestamp};
use crate::resolve::bucket_value;

#[derive(Clone, Debug)]
pub(crate) struct Expression {
    source: String,
    references: ExpressionReferences,
    /// The expression compiled by the `cel` engine. It drives both evaluation
    /// and the lint analysis (references, type constraints, result hint).
    cel_ast: IdedExpr,
}

#[derive(Clone, Debug, Default)]
pub(crate) struct ExpressionReferences {
    pub(crate) context_paths: BTreeSet<String>,
    pub(crate) entry_paths: BTreeSet<String>,
    /// Variable ids referenced through the `variables` root
    /// (`variables.some_id` / `variables["some_id"]`). The referenced variable's
    /// resolved value is bound in place, so expressions compose over other
    /// variables.
    pub(crate) variables: BTreeSet<String>,
    /// List ids referenced through the `lists` root (`lists.some_id` /
    /// `lists["some_id"]`). The reference binds the list's member list, so
    /// membership tests can name the set instead of restating its literals.
    pub(crate) lists: BTreeSet<String>,
    /// List memberships per context path (`context.<path> in lists.<id>`).
    /// The member type is not known at parse; lint refines the path's expected
    /// scalar family from the declared list.
    pub(crate) context_path_lists: BTreeMap<String, BTreeSet<String>>,
    /// Scalar types a context path is compared against, inferred from how the
    /// expression uses it. A path can carry more than one expectation when it is
    /// used in several places. Paths used in ways that do not pin a scalar type
    /// (for example the value argument of `bucket`) do not appear here.
    pub(crate) context_path_types: BTreeMap<String, BTreeSet<ContextScalarType>>,
    /// Root identifiers the expression uses that rototo does not provide. Lint
    /// turns these into diagnostics; evaluation would otherwise fail with cel's
    /// raw "undefined variable" error.
    pub(crate) invalid_roots: BTreeSet<ExpressionRootIssue>,
    /// Whether the expression references `env.resolving.*`, the entity being
    /// resolved. This is only available inside `[[trace]]` policies; lint rejects
    /// it elsewhere to keep rule and query evaluation independent of the caller.
    pub(crate) uses_resolving: bool,
}

/// A reference to a root identifier that is not part of rototo's evaluation
/// environment. The expression environment exposes exactly `context`, `entry`
/// (in queries), `variables`, `lists`, and `env` (with member `now`).
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum ExpressionRootIssue {
    /// The retired qualifier roots (`qualifier["<id>"]` and
    /// `env.qualifier["<id>"]`). Qualifiers dissolved into bool variables;
    /// kept distinct so the diagnostic can point at the replacement.
    LegacyQualifier,
    /// `env.<member>` where `<member>` is not a real env member.
    UnknownEnvMember(String),
    /// Any other unknown root identifier (e.g. a typo of `context`).
    UnknownRoot(String),
}

impl ExpressionRootIssue {
    pub(crate) fn describe(&self) -> String {
        match self {
            ExpressionRootIssue::LegacyQualifier => {
                "expression uses the retired qualifier root; qualifiers dissolved into bool \
                 variables, referenced as variables[\"<id>\"]"
                    .to_owned()
            }
            ExpressionRootIssue::UnknownEnvMember(member) => {
                format!("expression references unknown env member: env.{member}")
            }
            ExpressionRootIssue::UnknownRoot(root) => {
                format!("expression references unknown identifier: {root}")
            }
        }
    }
}

/// The JSON Schema scalar families an expression can require of a context path.
///
/// `Ip` and `Timestamp` are refined string families: the path must still be a
/// string, but it additionally has to carry the matching JSON Schema `format`
/// (`ipv4`/`ipv6`, `date-time`). They are inferred when a path is used as the
/// subject of `cidr`/time functions, and — now that catalog and evaluation
/// context validators assert formats — a declared `format` is a real value-level
/// guarantee, so requiring it here keeps those functions sound.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum ContextScalarType {
    Bool,
    Number,
    String,
    Ip,
    Timestamp,
}

impl ContextScalarType {
    /// Whether a JSON Schema `type` token names this scalar family. `integer`
    /// and `number` both satisfy a `Number` expectation; the refined string
    /// families are still `string` at the `type` level.
    pub(crate) fn matches_schema_type(self, schema_type: &str) -> bool {
        match self {
            ContextScalarType::Bool => schema_type == "boolean",
            ContextScalarType::Number => schema_type == "number" || schema_type == "integer",
            ContextScalarType::String | ContextScalarType::Ip | ContextScalarType::Timestamp => {
                schema_type == "string"
            }
        }
    }

    /// The JSON Schema `format` tokens that satisfy a refined string family. Any
    /// one of them is enough (an IP path may be declared `ipv4` or `ipv6`).
    /// Non-refined families impose no format requirement.
    pub(crate) fn required_formats(self) -> &'static [&'static str] {
        match self {
            ContextScalarType::Ip => &["ipv4", "ipv6"],
            ContextScalarType::Timestamp => &["date-time"],
            ContextScalarType::Bool | ContextScalarType::Number | ContextScalarType::String => &[],
        }
    }

    pub(crate) fn label(self) -> &'static str {
        match self {
            ContextScalarType::Bool => "boolean",
            ContextScalarType::Number => "number",
            ContextScalarType::String => "string",
            ContextScalarType::Ip => "an IP address",
            ContextScalarType::Timestamp => "a timestamp",
        }
    }
}

#[derive(Clone, Debug)]
pub(crate) struct ExpressionParseError {
    message: String,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ExpressionResultHint {
    Bool,
    Value,
}

impl ExpressionParseError {
    fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

impl std::fmt::Display for ExpressionParseError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for ExpressionParseError {}

impl Expression {
    pub(crate) fn parse(
        source: impl Into<String>,
    ) -> std::result::Result<Self, ExpressionParseError> {
        let source = source.into();
        let cel_ast = cel::Program::compile(&source)
            .map_err(|err| ExpressionParseError::new(err.to_string()))?
            .expression()
            .clone();
        let references = references_from_cel(&cel_ast);
        Ok(Self {
            source,
            references,
            cel_ast,
        })
    }

    pub(crate) fn source(&self) -> &str {
        &self.source
    }

    pub(crate) fn references(&self) -> &ExpressionReferences {
        &self.references
    }

    pub(crate) fn result_hint(&self) -> ExpressionResultHint {
        result_hint_from_cel(&self.cel_ast)
    }

    pub(crate) fn evaluate_bool(
        &self,
        context: &JsonValue,
        entry: Option<&JsonValue>,
        now: &str,
        refs: &mut dyn RefResolver,
    ) -> Result<bool> {
        let value = self.evaluate_value(context, entry, now, refs)?;
        value.as_bool().ok_or_else(|| {
            RototoError::new(format!(
                "expression did not evaluate to bool: {}",
                self.source
            ))
        })
    }

    pub(crate) fn evaluate_value(
        &self,
        context: &JsonValue,
        entry: Option<&JsonValue>,
        now: &str,
        refs: &mut dyn RefResolver,
    ) -> Result<JsonValue> {
        cel_evaluate(
            &self.cel_ast,
            &self.references,
            context,
            entry,
            now,
            None,
            refs,
        )
    }

    /// Evaluate a `[[trace]]` policy `when` to a bool, binding the entity being
    /// resolved as `env.resolving.*`. Only trace policies may reference
    /// `env.resolving`; other call sites use [`Expression::evaluate_bool`].
    pub(crate) fn evaluate_bool_traced(
        &self,
        context: &JsonValue,
        now: &str,
        resolving: ResolvingTarget<'_>,
        refs: &mut dyn RefResolver,
    ) -> Result<bool> {
        let value = cel_evaluate(
            &self.cel_ast,
            &self.references,
            context,
            None,
            now,
            Some(resolving),
            refs,
        )?;
        value.as_bool().ok_or_else(|| {
            RototoError::new(format!(
                "trace policy did not evaluate to bool: {}",
                self.source
            ))
        })
    }
}

/// Resolves the ids an expression references to their resolved values.
/// Implemented by the resolution state (memoized, cycle-checked) and by small
/// adapters at call sites that cannot or must not resolve references.
pub(crate) trait RefResolver {
    fn variable_value(&mut self, id: &str) -> Result<JsonValue>;
    /// The member list of a referenced list (`lists.<id>`), as a JSON array.
    fn list_members(&mut self, id: &str) -> Result<JsonValue>;
}

/// The entity being resolved, exposed to a `[[trace]]` policy `when` as
/// `env.resolving.variable`.
#[derive(Clone, Copy, Debug)]
pub(crate) enum ResolvingTarget<'a> {
    Variable(&'a str),
}

impl ResolvingTarget<'_> {
    fn to_env_value(self) -> JsonValue {
        let ResolvingTarget::Variable(id) = self;
        serde_json::json!({ "variable": id })
    }
}

// ---- Lint analysis over the cel AST. ----
// rototo's lint needs to know which context/entry paths and variables an
// expression references, the scalar type each context path is used as, and
// whether the expression is boolean-typed. All of this is derived from the cel
// `IdedExpr` the engine already parsed — there is no separate rototo parser.

mod eval;
mod references;
mod synthesize;
mod types;
mod upcoming;

pub(crate) use upcoming::TimeBoundary;

use eval::*;
use references::*;
pub(crate) use synthesize::{empty_context, merge_context};
use types::*;

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;

    use super::*;

    /// A fixed `env.now` so tests stay deterministic.
    const TEST_NOW: &str = "2026-06-29T00:00:00Z";

    /// A [`RefResolver`] over a fixed test table.
    struct TestRefs<'a> {
        variables: &'a [(&'a str, JsonValue)],
    }

    /// A [`RefResolver`] with a list table alongside the variable table.
    struct TestRefsWithLists<'a> {
        variables: &'a [(&'a str, JsonValue)],
        lists: &'a [(&'a str, JsonValue)],
    }

    impl RefResolver for TestRefs<'_> {
        fn variable_value(&mut self, id: &str) -> Result<JsonValue> {
            self.variables
                .iter()
                .find(|(variable, _)| *variable == id)
                .map(|(_, value)| value.clone())
                .ok_or_else(|| RototoError::new(format!("unknown variable: {id}")))
        }

        fn list_members(&mut self, id: &str) -> Result<JsonValue> {
            Err(RototoError::new(format!("unknown list: {id}")))
        }
    }

    impl RefResolver for TestRefsWithLists<'_> {
        fn variable_value(&mut self, id: &str) -> Result<JsonValue> {
            self.variables
                .iter()
                .find(|(variable, _)| *variable == id)
                .map(|(_, value)| value.clone())
                .ok_or_else(|| RototoError::new(format!("unknown variable: {id}")))
        }

        fn list_members(&mut self, id: &str) -> Result<JsonValue> {
            self.lists
                .iter()
                .find(|(list_id, _)| *list_id == id)
                .map(|(_, members)| members.clone())
                .ok_or_else(|| RototoError::new(format!("unknown list: {id}")))
        }
    }

    fn eval_bool(source: &str, context: &JsonValue, entry: Option<&JsonValue>) -> Result<bool> {
        eval_bool_with_variables(source, context, entry, &[])
    }

    fn eval_bool_with_variables(
        source: &str,
        context: &JsonValue,
        entry: Option<&JsonValue>,
        variables: &[(&str, JsonValue)],
    ) -> Result<bool> {
        let expr = Expression::parse(source).unwrap();
        let mut refs = TestRefs { variables };
        expr.evaluate_bool(context, entry, TEST_NOW, &mut refs)
    }

    fn eval_value(
        source: &str,
        context: &JsonValue,
        entry: Option<&JsonValue>,
    ) -> Result<JsonValue> {
        let expr = Expression::parse(source).unwrap();
        let mut refs = TestRefs { variables: &[] };
        expr.evaluate_value(context, entry, TEST_NOW, &mut refs)
    }

    fn string_set(values: &[&str]) -> BTreeSet<String> {
        values.iter().map(|value| (*value).to_owned()).collect()
    }

    #[test]
    fn parses_and_evaluates_basic_expression() {
        let expr =
            Expression::parse(r#"context.user.tier == "premium" && context.account.seats >= 10"#)
                .unwrap();
        let context = serde_json::json!({
            "user": { "tier": "premium" },
            "account": { "seats": 12 }
        });
        let mut refs = TestRefs { variables: &[] };
        assert!(
            expr.evaluate_bool(&context, None, TEST_NOW, &mut refs)
                .unwrap()
        );
    }

    fn context_types(source: &str) -> BTreeMap<String, BTreeSet<ContextScalarType>> {
        Expression::parse(source)
            .unwrap()
            .references()
            .context_path_types
            .clone()
    }

    #[test]
    fn infers_context_path_scalar_types_from_use() {
        use ContextScalarType::{Bool, Number, String};

        let eq = context_types(r#"context.user.tier == "premium""#);
        assert_eq!(eq.get("user.tier"), Some(&BTreeSet::from([String])));

        let ordering = context_types("context.account.seats >= 100");
        assert_eq!(
            ordering.get("account.seats"),
            Some(&BTreeSet::from([Number]))
        );

        let membership = context_types(r#"context.device.platform in ["ios","android"]"#);
        assert_eq!(
            membership.get("device.platform"),
            Some(&BTreeSet::from([String]))
        );

        let boolean = context_types("context.flags.enabled && context.user.tier == \"premium\"");
        assert_eq!(boolean.get("flags.enabled"), Some(&BTreeSet::from([Bool])));
        assert_eq!(boolean.get("user.tier"), Some(&BTreeSet::from([String])));

        let function = context_types(r#"semver(context.app.version, ">=1.2.0")"#);
        assert_eq!(function.get("app.version"), Some(&BTreeSet::from([String])));
    }

    #[test]
    fn infers_refined_string_types_from_cidr_and_time_functions() {
        use ContextScalarType::{Ip, Timestamp};

        let cidr = context_types(r#"cidr(context.user.ip, "10.0.0.0/8")"#);
        assert_eq!(cidr.get("user.ip"), Some(&BTreeSet::from([Ip])));

        let time = context_types(
            r#"timeBefore(context.window.start, "2026-01-01T00:00:00Z")
               && timeBetween(context.window.now, "2026-01-01T00:00:00Z", "2027-01-01T00:00:00Z")"#,
        );
        assert_eq!(time.get("window.start"), Some(&BTreeSet::from([Timestamp])));
        assert_eq!(time.get("window.now"), Some(&BTreeSet::from([Timestamp])));

        // semver stays a plain string: there is no enforced JSON Schema format.
        let semver = context_types(r#"semver(context.app.version, ">=1.0.0")"#);
        assert_eq!(
            semver.get("app.version"),
            Some(&BTreeSet::from([ContextScalarType::String]))
        );
    }

    #[test]
    fn leaves_bucket_value_argument_unconstrained() {
        let types = context_types(r#"bucket(context.user.id, "salt", 0, 1000)"#);
        assert!(
            !types.contains_key("user.id"),
            "bucket's value argument should not pin a scalar type: {types:?}"
        );
    }

    #[test]
    fn records_conflicting_uses_as_multiple_expectations() {
        use ContextScalarType::{Number, String};
        let types = context_types(r#"context.x == "a" && context.x >= 5"#);
        assert_eq!(types.get("x"), Some(&BTreeSet::from([String, Number])));
    }

    #[test]
    fn tracks_variable_and_entry_references() {
        let expr = Expression::parse(
            r#"variables["enterprise_accounts"] && entry.id == "hero" && context.region == "eu""#,
        )
        .unwrap();
        assert!(expr.references().variables.contains("enterprise_accounts"));
        assert!(expr.references().entry_paths.contains("id"));
        assert!(expr.references().context_paths.contains("region"));
    }

    #[test]
    fn tracks_variable_references_in_both_spellings() {
        let expr = Expression::parse(
            r#"variables.premium_user && variables["beta_cohort"] && "sso" in variables.plan_features"#,
        )
        .unwrap();
        assert_eq!(
            expr.references().variables,
            string_set(&["premium_user", "beta_cohort", "plan_features"])
        );
        // The variables root is provided by rototo, never an unknown root, and
        // extra trailing segments select into the referenced variable's value.
        let nested = Expression::parse(r#"variables.limits.max_seats >= 5"#).unwrap();
        assert!(nested.references().invalid_roots.is_empty());
        assert_eq!(nested.references().variables, string_set(&["limits"]));
    }

    #[test]
    fn evaluates_variable_references() {
        let context = serde_json::json!({});
        let expr =
            Expression::parse(r#"variables["premium_user"] && variables.message == "on""#).unwrap();
        let mut refs = TestRefs {
            variables: &[
                ("premium_user", JsonValue::Bool(true)),
                ("message", serde_json::json!("on")),
            ],
        };
        assert!(
            expr.evaluate_bool(&context, None, TEST_NOW, &mut refs)
                .unwrap()
        );

        // Selecting into a referenced variable's structured value.
        let expr = Expression::parse(r#"variables.limits.max_seats >= 5"#).unwrap();
        let mut refs = TestRefs {
            variables: &[("limits", serde_json::json!({ "max_seats": 12 }))],
        };
        assert!(
            expr.evaluate_bool(&context, None, TEST_NOW, &mut refs)
                .unwrap()
        );

        // An unknown variable surfaces the resolver's error.
        let expr = Expression::parse(r#"variables.missing"#).unwrap();
        let mut refs = TestRefs { variables: &[] };
        let err = expr
            .evaluate_bool(&context, None, TEST_NOW, &mut refs)
            .unwrap_err();
        assert!(err.to_string().contains("unknown variable: missing"));
    }

    #[test]
    fn synthesizes_contexts_through_variable_references() {
        let premium = Expression::parse(r#"context.user.tier == "premium""#).unwrap();
        let expr = Expression::parse(r#"variables["premium_user"] && context.account.seats >= 50"#)
            .unwrap();
        let context = expr
            .synthesize_context(
                true,
                &mut |id, want| {
                    assert_eq!(id, "premium_user");
                    premium.synthesize_context(want, &mut |_, _| None, &mut |_| None)
                },
                &mut |_| None,
            )
            .expect("expected composed synthesis");
        assert_eq!(
            context,
            serde_json::json!({
                "user": { "tier": "premium" },
                "account": { "seats": 50 }
            })
        );
    }

    #[test]
    fn evaluates_env_members() {
        let context = serde_json::json!({});
        // env.now is the RFC3339 timestamp threaded into evaluation; it reads as
        // a plain string and feeds the time functions.
        assert!(eval_bool(r#"env.now == "2026-06-29T00:00:00Z""#, &context, None).unwrap());
        assert!(
            eval_bool(
                r#"timeAtOrAfter(env.now, "2020-01-01T00:00:00Z")"#,
                &context,
                None,
            )
            .unwrap()
        );
        // variables binds the resolved values of referenced variables.
        assert!(
            eval_bool_with_variables(
                r#"variables["beta"]"#,
                &context,
                None,
                &[("beta", JsonValue::Bool(true))],
            )
            .unwrap()
        );
    }

    #[test]
    fn flags_invalid_expression_roots() {
        use ExpressionRootIssue::{LegacyQualifier, UnknownEnvMember, UnknownRoot};

        let legacy = Expression::parse(r#"qualifier["x"]"#).unwrap();
        assert!(legacy.references().invalid_roots.contains(&LegacyQualifier));

        let bad_env = Expression::parse("env.bogus").unwrap();
        assert!(
            bad_env
                .references()
                .invalid_roots
                .contains(&UnknownEnvMember("bogus".to_owned()))
        );

        let unknown = Expression::parse("foo.bar").unwrap();
        assert!(
            unknown
                .references()
                .invalid_roots
                .contains(&UnknownRoot("foo".to_owned()))
        );

        // The retired env.qualifier spelling gets the pointed legacy diagnostic.
        let env_qualifier = Expression::parse(r#"env.qualifier["x"]"#).unwrap();
        assert!(
            env_qualifier
                .references()
                .invalid_roots
                .contains(&LegacyQualifier)
        );

        // Valid roots produce no issues.
        let ok = Expression::parse(
            r#"variables["x"] && env.now == "" && context.a == 1 && entry.b == 2
               && context.tier in lists.plan_tiers"#,
        )
        .unwrap();
        assert!(ok.references().invalid_roots.is_empty());
    }

    #[test]
    fn tracks_list_references_in_both_spellings() {
        let expr = Expression::parse(
            r#"context.tier in lists.plan_tiers && context.region in lists["geo/regions"]"#,
        )
        .unwrap();
        assert!(expr.references().invalid_roots.is_empty());
        assert_eq!(
            expr.references().lists,
            string_set(&["plan_tiers", "geo/regions"])
        );
        // The membership pairs the context path with the list whose members
        // constrain it; lint refines the path's expected type from the list.
        assert_eq!(
            expr.references().context_path_lists.get("tier"),
            Some(&string_set(&["plan_tiers"]))
        );
        assert_eq!(
            expr.references().context_path_lists.get("region"),
            Some(&string_set(&["geo/regions"]))
        );
    }

    #[test]
    fn evaluates_list_membership() {
        let context = serde_json::json!({ "tier": "team" });
        let expr = Expression::parse(r#"context.tier in lists.plan_tiers"#).unwrap();
        let members = serde_json::json!(["free", "team", "business"]);

        let mut refs = TestRefsWithLists {
            variables: &[],
            lists: &[("plan_tiers", members.clone())],
        };
        assert!(
            expr.evaluate_bool(&context, None, TEST_NOW, &mut refs)
                .unwrap()
        );

        let outside = serde_json::json!({ "tier": "trial" });
        let mut refs = TestRefsWithLists {
            variables: &[],
            lists: &[("plan_tiers", members.clone())],
        };
        assert!(
            !expr
                .evaluate_bool(&outside, None, TEST_NOW, &mut refs)
                .unwrap()
        );

        // The member list is an ordinary CEL list value, so size() and
        // comprehensions compose with it.
        let size = Expression::parse("size(lists.plan_tiers) == 3").unwrap();
        let mut refs = TestRefsWithLists {
            variables: &[],
            lists: &[("plan_tiers", members)],
        };
        assert!(
            size.evaluate_bool(&context, None, TEST_NOW, &mut refs)
                .unwrap()
        );

        // An unknown list surfaces the resolver's error.
        let mut refs = TestRefsWithLists {
            variables: &[],
            lists: &[],
        };
        let err = expr
            .evaluate_bool(&context, None, TEST_NOW, &mut refs)
            .unwrap_err();
        assert!(err.to_string().contains("unknown list: plan_tiers"));
    }

    #[test]
    fn synthesizes_list_membership() {
        let source = r#"context.tier in lists.plan_tiers"#;
        let expr = Expression::parse(source).unwrap();
        let members = vec![
            serde_json::json!("free"),
            serde_json::json!("team"),
            serde_json::json!("business"),
        ];

        for want in [true, false] {
            let context = expr
                .synthesize_context(want, &mut |_, _| None, &mut |id| {
                    assert_eq!(id, "plan_tiers");
                    Some(members.clone())
                })
                .expect("expected list membership synthesis");
            let mut refs = TestRefsWithLists {
                variables: &[],
                lists: &[(
                    "plan_tiers",
                    serde_json::json!(["free", "team", "business"]),
                )],
            };
            assert_eq!(
                expr.evaluate_bool(&context, None, TEST_NOW, &mut refs)
                    .unwrap(),
                want,
                "synthesized context {context} did not evaluate to {want}"
            );
        }

        // Without list data the membership is honestly uninvertible.
        assert!(
            expr.synthesize_context(true, &mut |_, _| None, &mut |_| None)
                .is_none()
        );
    }

    #[test]
    fn comprehension_bound_identifiers_are_not_unknown_roots() {
        // Macros such as exists() expand to comprehensions whose iteration
        // variable is a bare identifier; chains rooted at it are bindings,
        // not references.
        let expression =
            Expression::parse("entry.audiences.exists(a, a.min_visits <= context.visits)").unwrap();
        let references = expression.references();
        assert!(references.invalid_roots.is_empty());
        assert!(references.entry_paths.contains("audiences"));
        assert!(references.context_paths.contains("visits"));

        // The binding does not leak: the same identifier outside the
        // comprehension is still an unknown root.
        let outside = Expression::parse("entry.list.exists(a, a.x) && a.y").unwrap();
        assert!(
            outside
                .references()
                .invalid_roots
                .contains(&ExpressionRootIssue::UnknownRoot("a".to_owned()))
        );
    }

    #[test]
    fn evaluates_logical_precedence_and_short_circuiting() {
        let context = serde_json::json!({});

        assert!(eval_bool("true || false && false", &context, None).unwrap());
        assert!(!eval_bool("(true || false) && false", &context, None).unwrap());
        assert!(eval_bool("!false && (false || true)", &context, None).unwrap());

        // Variables referenced by an expression are resolved eagerly (the cel
        // engine indexes a precomputed map), so the resolver runs regardless of
        // short-circuiting; it simply returns a value here.
        assert!(
            eval_bool_with_variables(
                r#"true || variables["must_not_run"]"#,
                &context,
                None,
                &[("must_not_run", JsonValue::Bool(false))],
            )
            .unwrap()
        );
        assert!(
            !eval_bool_with_variables(
                r#"false && variables["must_not_run"]"#,
                &context,
                None,
                &[("must_not_run", JsonValue::Bool(false))],
            )
            .unwrap()
        );
    }

    #[test]
    fn evaluates_comparison_membership_and_json_equality() {
        let context = serde_json::json!({
            "enabled": true,
            "optional": null,
            "seats": 42,
            "ratio": 2.5,
            "tier": "premium",
            "tags": ["a", "b"]
        });

        let cases = [
            (r#"context.seats == 42.0"#, true),
            (r#"context.seats != 43"#, true),
            (r#"context.seats < 43 && context.seats <= 42"#, true),
            (r#"context.ratio > 2 && context.ratio >= 2.5"#, true),
            (r#""bravo" > "alpha" && "alpha" <= "alpha""#, true),
            (r#"context.tier in ["free", "premium"]"#, true),
            (r#""b" in context.tags"#, true),
            (
                r#"context.optional == null && context.enabled == true"#,
                true,
            ),
            (r#"context.tags == ["a", "b"]"#, true),
            // Heterogeneous equality is false (not an error) under cel.
            (r#"context.seats == "42""#, false),
            // Cross-type ordering (`context.tier > 10`) and membership in a
            // non-collection (`context.tier in "premium"`) are no-overload
            // errors in cel, and the schema-aware checker rejects them at lint;
            // they are not exercised here.
        ];

        for (source, expected) in cases {
            assert_eq!(
                eval_bool(source, &context, None).unwrap(),
                expected,
                "{source}"
            );
        }
    }

    #[test]
    fn evaluates_context_paths_entry_paths_and_variables() {
        let context = serde_json::json!({
            "account.plan": "enterprise",
            "account": {
                "seat-count": 12
            },
            "channel": "email"
        });
        let entry = serde_json::json!({
            "channel": "email",
            "active": true,
            "limits": {
                "daily": 100
            }
        });

        assert!(
            eval_bool(
                r#"context["account.plan"] == "enterprise" && context.account["seat-count"] == 12"#,
                &context,
                None,
            )
            .unwrap()
        );
        assert!(
            eval_bool(
                r#"entry.channel == context.channel && entry.active == true && entry.limits.daily >= 100"#,
                &context,
                Some(&entry),
            )
            .unwrap()
        );
        assert!(
            eval_bool_with_variables(
                r#"variables["enterprise_accounts"] && variables["mobile_users"]"#,
                &context,
                None,
                &[
                    ("enterprise_accounts", JsonValue::Bool(true)),
                    ("mobile_users", JsonValue::Bool(true)),
                ],
            )
            .unwrap()
        );
    }

    #[test]
    fn evaluates_supported_functions() {
        let context = serde_json::json!({
            "user": {
                "id": "user-42",
                "email": "owner@rototo.dev",
                "ip": "192.168.1.10",
                "version": "1.4.2",
                "created_at": "2026-06-21T12:30:00Z"
            },
            "payload": {
                "features": ["checkout", "support"],
                "nested": { "name": "rototo" }
            },
            "tags": ["alpha", "beta"]
        });

        let cases = [
            (r#"has(context.user.id)"#, true),
            (r#"has(context.user.missing)"#, false),
            (r#"present(context.payload, "/features/0")"#, true),
            (r#"missing(context.payload, "/features/3")"#, true),
            (r#"startsWith(context.user.email, "owner@")"#, true),
            (r#"ends_with(context.user.email, ".dev")"#, true),
            (r#"contains(context.user.email, "rototo")"#, true),
            (r#"contains(context.tags, "beta")"#, true),
            (
                r#"matches(context.user.email, "^[^@]+@rototo\\.dev$")"#,
                true,
            ),
            (r#"glob(context.user.email, "*@rototo.dev")"#, true),
            (r#"semver(context.user.version, ">=1.0, <2.0")"#, true),
            (
                r#"timeBetween(context.user.created_at, "2026-06-21T00:00:00Z", "2026-06-22T00:00:00Z")"#,
                true,
            ),
            (
                r#"timeAfter(context.user.created_at, "2026-06-21T00:00:00Z")"#,
                true,
            ),
            (
                r#"timeBefore(context.user.created_at, "2026-06-22T00:00:00Z")"#,
                true,
            ),
            (
                r#"time_at_or_before(context.user.created_at, "2026-06-21T12:30:00Z")"#,
                true,
            ),
            (
                r#"time_at_or_after(context.user.created_at, "2026-06-21T12:30:00Z")"#,
                true,
            ),
            (r#"cidr(context.user.ip, "192.168.1.0/24")"#, true),
            (r#"inCidr(context.user.ip, "192.168.1.0/24")"#, true),
            (r#"in_cidr(context.user.ip, "10.0.0.0/8")"#, false),
            (
                r#"cidr(context.user.ip, ["10.0.0.0/8", "192.168.0.0/16"])"#,
                true,
            ),
            (r#"bucket(context.user.id, "rollout", 0, 65536)"#, true),
            (r#"bucket(context.user.id, "rollout", 65536, 65537)"#, false),
        ];

        for (source, expected) in cases {
            assert_eq!(
                eval_bool(source, &context, None).unwrap(),
                expected,
                "{source}"
            );
        }

        assert_eq!(
            eval_value(r#"path(context.payload, "/nested/name")"#, &context, None).unwrap(),
            serde_json::json!("rototo")
        );
        assert_eq!(
            eval_value("size(context.tags)", &context, None).unwrap(),
            serde_json::json!(2)
        );
    }

    #[test]
    fn rejects_malformed_expressions_at_parse() {
        // Syntactically malformed expressions fail to compile. Exact messages
        // come from the cel parser, so the contract is "rejected at parse".
        // (Bare unknown identifiers like `account.tier` are valid cel and are
        // caught later by the schema-aware reference checks, not here.)
        let malformed = [
            r#"context.user.tier = "premium""#, // single `=`
            "context.user.",                    // trailing dot
            r#"context.user.tier == "premium"#, // unterminated string
            "true false",                       // two expressions
            "(context.user.tier",               // unbalanced paren
        ];

        for source in malformed {
            assert!(
                Expression::parse(source).is_err(),
                "{source}: expected a parse error"
            );
        }
    }

    #[test]
    fn reports_evaluation_errors_with_stable_messages() {
        let context = serde_json::json!({
            "user": {
                "tier": "premium"
            },
            "payload": {}
        });

        // These all fail at evaluation. Exact messages now come from the cel
        // engine, so the contract is "evaluation errors", not a specific string.
        let error_cases = [
            "context.user.missing == true",                 // missing context key
            "entry.channel == \"email\"",                   // no entry provided
            "context.user.tier && true",                    // non-bool operand
            "unknown_fn(context.user.tier)",                // unknown function
            "size(true)",                                   // size of a non-collection
            r#"path(context.payload, "/missing") == true"#, // missing JSON pointer
            r#"regex(context.user.tier, "[")"#,             // invalid regex
            r#"cidr(context.user.tier, "not-cidr")"#,       // invalid ip
        ];

        for source in error_cases {
            assert!(
                eval_bool(source, &context, None).is_err(),
                "{source}: expected an evaluation error"
            );
        }

        let err = eval_bool(r#""premium""#, &context, None).unwrap_err();
        assert_eq!(
            err.to_string(),
            r#"expression did not evaluate to bool: "premium""#
        );
    }

    #[test]
    fn extracts_references_from_nested_paths_functions_and_variables() {
        let expr = Expression::parse(
            r#"
            variables["enterprise_accounts"]
                && variables["mobile_users"]
                && has(context.user.tier)
                && context.request.country in ["DE", "NL"]
                && entry.metadata.channel == context.channel
                && path(entry.payload, "/title") == "Welcome"
            "#,
        )
        .unwrap();
        let references = expr.references();

        assert_eq!(
            references.variables,
            string_set(&["enterprise_accounts", "mobile_users"])
        );
        assert_eq!(
            references.context_paths,
            string_set(&["channel", "request.country", "user.tier"])
        );
        assert_eq!(
            references.entry_paths,
            string_set(&["metadata.channel", "payload"])
        );
    }

    /// Synthesize a context for `source` with no variable composition.
    fn synth(source: &str, want: bool) -> Option<JsonValue> {
        Expression::parse(source)
            .unwrap()
            .synthesize_context(want, &mut |_, _| None, &mut |_| None)
    }

    /// Synthesizing for an outcome and evaluating against the result must
    /// reproduce that outcome. This round-trip is the property fixtures rely on.
    fn assert_round_trip(source: &str) {
        for want in [true, false] {
            let context = synth(source, want)
                .unwrap_or_else(|| panic!("expected synthesis for {source} (want={want})"));
            assert_eq!(
                eval_bool(source, &context, None).unwrap(),
                want,
                "synthesized context {context} for {source} did not evaluate to {want}",
            );
        }
    }

    #[test]
    fn synthesizes_equality_and_inequality() {
        assert_round_trip(r#"context.account.tier == "standard""#);
        assert_round_trip(r#"context.account.tier != "free""#);
        assert_round_trip("context.flags.enabled");
    }

    #[test]
    fn synthesizes_orderings() {
        assert_round_trip("context.account.seats >= 100");
        assert_round_trip("context.cart.total_usd > 250");
        assert_round_trip("context.user.age < 18");
        // Literal written on the left flips the relation direction.
        assert_round_trip("100 <= context.account.seats");
    }

    #[test]
    fn synthesizes_membership() {
        assert_round_trip(r#"context.request.country in ["DE", "FR", "ES"]"#);
        assert_round_trip("context.account.seats in [10, 20, 30]");
    }

    #[test]
    fn synthesizes_boolean_composition() {
        assert_round_trip(r#"context.user.tier == "premium" && context.account.seats >= 100"#);
        assert_round_trip(r#"context.lane == "dev" || context.lane == "stage""#);
        assert_round_trip(r#"!(context.user.tier == "free")"#);
    }

    #[test]
    fn synthesizes_bucket() {
        assert_round_trip(r#"bucket(context.user.id, "rollout-salt", 0, 1000)"#);
    }

    #[test]
    fn synthesizes_through_condition_composition() {
        // `variables["premium"]` is satisfied by recursively synthesizing the
        // referenced condition variable's own expression and merging its
        // context in.
        let premium = Expression::parse(r#"context.user.tier == "premium""#).unwrap();
        let source = r#"variables["premium"] && context.account.seats >= 50"#;
        let expr = Expression::parse(source).unwrap();
        let context = expr
            .synthesize_context(
                true,
                &mut |id, want| {
                    assert_eq!(id, "premium");
                    premium.synthesize_context(want, &mut |_, _| None, &mut |_| None)
                },
                &mut |_| None,
            )
            .expect("expected composed synthesis");

        let mut refs = TestRefs { variables: &[] };
        let premium_value = premium
            .evaluate_bool(&context, None, TEST_NOW, &mut refs)
            .unwrap();
        assert!(
            eval_bool_with_variables(
                source,
                &context,
                None,
                &[("premium", JsonValue::Bool(premium_value))],
            )
            .unwrap()
        );
    }

    #[test]
    fn returns_none_for_uninvertible_shapes() {
        // A free-form string function the synthesizer does not model.
        assert!(synth(r#"context.user.email.endsWith("@rototo.dev")"#, true).is_none());
    }

    #[test]
    fn bucket_synthesis_gives_up_after_the_candidate_budget() {
        // An empty bucket range is never satisfiable; the candidate search
        // stops at MAX_BUCKET_CANDIDATES and reports no context instead of
        // spinning forever.
        assert!(synth(r#"bucket(context.user.id, "salt", 7, 7)"#, true).is_none());
    }
}