billdogeng 1.0.0-beta.1

Official BilldogEng server SDK for Rust — Analytics, Feature Flags (remote + local eval), Surveys, Messaging, and LLM observability.
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
//! Feature-flag client supporting both remote and local (server-side) evaluation.
//!
//! Local evaluation (`local_evaluation: true`) fetches flag DEFINITIONS once,
//! caches them with a 5-minute TTL, and evaluates each flag deterministically
//! on this process — the correct home for flag evaluation in a server SDK and
//! the cross-platform-identical algorithm shared with web / iOS / Android.
//!
//! Remote evaluation falls back to `POST /experiment-config`, which returns a
//! pre-evaluated `feature_flags` map for the given user.

use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant};

use serde_json::{json, Value};

use crate::error::Result;
use crate::murmur::murmurhash3;
use crate::transport::{RequestOptions, Transport};
use crate::types::{
    FeatureFlagDefinition, FlagEvalOptions, FlagValue, Operator, Properties, TargetingRule,
};

/// TTL for cached flag definitions: 5 minutes (spec §D).
const FLAG_DEFINITIONS_TTL: Duration = Duration::from_secs(5 * 60);

struct Cache {
    definitions: HashMap<String, FeatureFlagDefinition>,
    fetched_at: Option<Instant>,
}

/// Feature-flag client.
pub struct Flags {
    transport: Transport,
    api_key: String,
    local_evaluation: bool,
    enable_logging: bool,
    cache: Mutex<Cache>,
}

impl Flags {
    /// Construct the flags client.
    pub fn new(
        transport: Transport,
        api_key: String,
        local_evaluation: bool,
        enable_logging: bool,
    ) -> Self {
        Self {
            transport,
            api_key,
            local_evaluation,
            enable_logging,
            cache: Mutex::new(Cache {
                definitions: HashMap::new(),
                fetched_at: None,
            }),
        }
    }

    fn log(&self, msg: &str) {
        if self.enable_logging {
            eprintln!("[BilldogEng:flags] {msg}");
        }
    }

    /// Get a flag's value for a user.
    ///
    /// Returns `Some(FlagValue::Bool)` for a simple flag, `Some(FlagValue::Variant)`
    /// for a multivariate flag, or `None` when the flag is unknown.
    pub fn get_feature_flag(
        &self,
        key: &str,
        distinct_id: &str,
        opts: &FlagEvalOptions,
    ) -> Result<Option<FlagValue>> {
        if self.local_evaluation {
            self.ensure_definitions()?;
            let cache = self.cache.lock().unwrap();
            if !cache.definitions.contains_key(key) {
                return Ok(None);
            }
            let def = cache.definitions.get(key).cloned();
            drop(cache);
            return Ok(Some(evaluate_def(
                def.as_ref(),
                key,
                distinct_id,
                opts.person_properties.as_ref(),
            )));
        }
        let map = self.fetch_remote(distinct_id, opts.person_properties.as_ref())?;
        match map.get(key) {
            None => Ok(None),
            Some(Value::Bool(b)) => Ok(Some(FlagValue::Bool(*b))),
            Some(Value::String(s)) => Ok(Some(FlagValue::Variant(s.clone()))),
            Some(_) => Ok(Some(FlagValue::Bool(true))),
        }
    }

    /// Boolean view of [`get_feature_flag`](Self::get_feature_flag) (a variant
    /// string counts as ON).
    pub fn is_feature_enabled(
        &self,
        key: &str,
        distinct_id: &str,
        opts: &FlagEvalOptions,
    ) -> Result<bool> {
        Ok(self
            .get_feature_flag(key, distinct_id, opts)?
            .map(|v| v.is_enabled())
            .unwrap_or(false))
    }

    /// Get a flag's payload (variant config). Only meaningful under local
    /// evaluation. Returns the matched variant's payload, else the flag-level
    /// payload, else `None`.
    pub fn get_feature_flag_payload(
        &self,
        key: &str,
        distinct_id: &str,
        opts: &FlagEvalOptions,
    ) -> Result<Option<Value>> {
        self.ensure_definitions()?;
        let cache = self.cache.lock().unwrap();
        let def = match cache.definitions.get(key) {
            Some(d) => d.clone(),
            None => return Ok(None),
        };
        drop(cache);

        let verdict = evaluate_def(Some(&def), key, distinct_id, opts.person_properties.as_ref());
        match verdict {
            FlagValue::Bool(false) => Ok(None),
            FlagValue::Variant(ref vkey) => {
                if let Some(variants) = &def.variants {
                    if let Some(v) = variants.iter().find(|v| &v.key == vkey) {
                        if let Some(p) = &v.payload {
                            return Ok(Some(p.clone()));
                        }
                    }
                }
                Ok(def.payload.clone())
            }
            FlagValue::Bool(true) => Ok(def.payload.clone()),
        }
    }

    /// Evaluate every known flag for a user.
    pub fn get_all_flags(
        &self,
        distinct_id: &str,
        opts: &FlagEvalOptions,
    ) -> Result<HashMap<String, FlagValue>> {
        if self.local_evaluation {
            self.ensure_definitions()?;
            let cache = self.cache.lock().unwrap();
            let defs: Vec<(String, FeatureFlagDefinition)> = cache
                .definitions
                .iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect();
            drop(cache);
            let mut out = HashMap::new();
            for (key, def) in defs {
                out.insert(
                    key.clone(),
                    evaluate_def(Some(&def), &key, distinct_id, opts.person_properties.as_ref()),
                );
            }
            return Ok(out);
        }
        let map = self.fetch_remote(distinct_id, opts.person_properties.as_ref())?;
        let mut out = HashMap::new();
        for (k, v) in map {
            let fv = match v {
                Value::Bool(b) => FlagValue::Bool(b),
                Value::String(s) => FlagValue::Variant(s),
                _ => FlagValue::Bool(true),
            };
            out.insert(k, fv);
        }
        Ok(out)
    }

    /// Force a reload of the cached flag definitions (local mode).
    pub fn reload_feature_flag_definitions(&self) -> Result<()> {
        self.fetch_definitions()
    }

    /// Inject flag definitions directly, bypassing the network. Primarily for
    /// tests and for hosts that distribute definitions through their own channel.
    pub fn set_definitions(&self, defs: Vec<FeatureFlagDefinition>) {
        let mut cache = self.cache.lock().unwrap();
        cache.definitions = defs.into_iter().map(|d| (d.key.clone(), d)).collect();
        cache.fetched_at = Some(Instant::now());
    }

    // ─── Internals ──────────────────────────────────────────────────────────

    fn ensure_definitions(&self) -> Result<()> {
        {
            let cache = self.cache.lock().unwrap();
            let fresh = !cache.definitions.is_empty()
                && cache
                    .fetched_at
                    .map(|t| t.elapsed() < FLAG_DEFINITIONS_TTL)
                    .unwrap_or(false);
            if fresh {
                return Ok(());
            }
        }
        self.fetch_definitions()
    }

    fn fetch_definitions(&self) -> Result<()> {
        let opts = RequestOptions::post(
            "/feature-flag-definitions",
            json!({ "api_key": self.api_key }),
        )
        .header("x-api-key", &self.api_key)
        .gzip(false);

        match self.transport.request(&opts) {
            Ok(data) => {
                let flags: Vec<FeatureFlagDefinition> = data
                    .get("flags")
                    .and_then(|v| serde_json::from_value(v.clone()).ok())
                    .unwrap_or_default();
                let mut cache = self.cache.lock().unwrap();
                cache.definitions = flags.into_iter().map(|d| (d.key.clone(), d)).collect();
                cache.fetched_at = Some(Instant::now());
                self.log(&format!(
                    "loaded {} flag definitions",
                    cache.definitions.len()
                ));
                Ok(())
            }
            Err(e) => {
                // Graceful: keep any existing cache; surface in logs only.
                self.log(&format!("failed to load flag definitions: {}", e.message));
                Ok(())
            }
        }
    }

    fn fetch_remote(
        &self,
        distinct_id: &str,
        attributes: Option<&Properties>,
    ) -> Result<HashMap<String, Value>> {
        let attrs = attributes.cloned().unwrap_or_default();
        let opts = RequestOptions::post(
            "/experiment-config",
            json!({
                "api_key": self.api_key,
                "user_id": distinct_id,
                "attributes": attrs,
            }),
        )
        .header("x-api-key", &self.api_key)
        .gzip(false);

        let data = self.transport.request(&opts)?;
        let map = data
            .get("feature_flags")
            .and_then(|v| v.as_object())
            .map(|o| o.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
            .unwrap_or_default();
        Ok(map)
    }
}

/// Deterministic local flag evaluation (spec §D):
///  1. Missing/inactive → false.
///  2. ALL `targeting_rules` must match `attributes`, else false.
///  3. bucket = murmurhash3("{key}.{distinctId}") % 100; ON iff bucket < rollout.
///  4. Multivariate: walk variants by cumulative rollout within the ON bucket.
pub fn evaluate_def(
    def: Option<&FeatureFlagDefinition>,
    key: &str,
    distinct_id: &str,
    attributes: Option<&Properties>,
) -> FlagValue {
    let def = match def {
        Some(d) if d.active => d,
        _ => return FlagValue::Bool(false),
    };

    if let Some(rules) = &def.targeting_rules {
        let empty = Properties::new();
        let attrs = attributes.unwrap_or(&empty);
        for rule in rules {
            if !matches_rule(rule, attrs.get(&rule.attribute)) {
                return FlagValue::Bool(false);
            }
        }
    }

    let bucket = murmurhash3(&format!("{key}.{distinct_id}")) % 100;
    if bucket >= def.rollout_percentage {
        return FlagValue::Bool(false);
    }

    if let Some(variants) = &def.variants {
        if !variants.is_empty() {
            let mut cumulative = 0u32;
            for variant in variants {
                cumulative += variant.rollout_percentage;
                if bucket < cumulative {
                    return FlagValue::Variant(variant.key.clone());
                }
            }
            // bucket beyond declared variants → on, no specific variant.
            return FlagValue::Bool(true);
        }
    }

    FlagValue::Bool(true)
}

/// Stringify a JSON value the way the backend's `toComparable` / `String()`
/// does: `null`/absent → `None`; strings unquoted; everything else via its
/// JSON scalar form. Mirrors `pure.ts`'s `String(actual)` semantics for the
/// scalar shapes a targeting attribute can take.
fn to_comparable(v: &Value) -> Option<String> {
    match v {
        Value::Null => None,
        Value::String(s) => Some(s.clone()),
        Value::Bool(b) => Some(b.to_string()),
        Value::Number(n) => Some(n.to_string()),
        // Arrays/objects are not expected as `actual`; fall back to JSON.
        other => Some(other.to_string()),
    }
}

/// `String(expected)` for the right-hand side of a comparison.
fn expected_string(v: &Value) -> String {
    match v {
        Value::String(s) => s.clone(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
        Value::Null => "null".to_string(),
        other => other.to_string(),
    }
}

/// Mirror of `pure.ts` `compare(operator, actual, expected)`.
///
/// `value` is the attribute looked up from the property bag (`None` = absent).
fn matches_rule(rule: &TargetingRule, value: Option<&Value>) -> bool {
    let actual = value.unwrap_or(&Value::Null);
    let actual_string = to_comparable(actual);
    let expected = &rule.value;

    // exists / not_exists handle the absent case before the null short-circuit.
    match rule.operator {
        Operator::Exists => {
            return matches!(&actual_string, Some(s) if !s.is_empty());
        }
        Operator::NotExists => {
            return match &actual_string {
                None => true,
                Some(s) => s.is_empty(),
            };
        }
        _ => {}
    }

    // For all other operators: absent/null actual → false.
    let actual_string = match actual_string {
        Some(s) => s,
        None => return false,
    };

    match rule.operator {
        Operator::Is | Operator::Equals => actual_string == expected_string(expected),
        Operator::IsNot | Operator::NotEquals => actual_string != expected_string(expected),
        Operator::AnyOf => match expected.as_array() {
            Some(arr) => arr.iter().any(|e| expected_string(e) == actual_string),
            None => false,
        },
        Operator::NotAnyOf => match expected.as_array() {
            Some(arr) => !arr.iter().any(|e| expected_string(e) == actual_string),
            None => false,
        },
        Operator::Contains => actual_string.contains(&expected_string(expected)),
        Operator::NotContains => !actual_string.contains(&expected_string(expected)),
        Operator::GreaterThan | Operator::Gt => {
            compare_ordered(&actual_string, expected, |o| o == std::cmp::Ordering::Greater)
        }
        Operator::LessThan | Operator::Lt => {
            compare_ordered(&actual_string, expected, |o| o == std::cmp::Ordering::Less)
        }
        Operator::GreaterThanOrEqual | Operator::Gte => compare_ordered(&actual_string, expected, |o| {
            o == std::cmp::Ordering::Greater || o == std::cmp::Ordering::Equal
        }),
        Operator::LessThanOrEqual | Operator::Lte => compare_ordered(&actual_string, expected, |o| {
            o == std::cmp::Ordering::Less || o == std::cmp::Ordering::Equal
        }),
        // exists / not_exists handled above.
        Operator::Exists | Operator::NotExists => false,
    }
}

/// Date-or-number ordered comparison, mirroring `pure.ts`: if BOTH `actual`
/// and `expected` parse as ISO dates, compare their epoch instants; otherwise
/// fall back to numeric `Number(actual) <op> Number(expected)`.
fn compare_ordered(actual_string: &str, expected: &Value, pred: impl Fn(std::cmp::Ordering) -> bool) -> bool {
    let expected_string = expected_string(expected);
    if let (Some(a), Some(b)) = (try_parse_date(actual_string), try_parse_date(&expected_string)) {
        return pred(a.cmp(&b));
    }
    let a = actual_string.parse::<f64>().unwrap_or(f64::NAN);
    let b = expected_string.parse::<f64>().unwrap_or(f64::NAN);
    match a.partial_cmp(&b) {
        Some(ord) => pred(ord),
        None => false, // NaN — JS comparisons against NaN are all false.
    }
}

/// Mirror of `pure.ts` `tryParseDate`: only treat a value as a date when it
/// matches `^\d{4}-\d{2}-\d{2}` AND parses to a valid instant. Returns a
/// comparable epoch-millisecond value. chrono is not a dependency, so this is
/// a manual ISO-8601 parser covering the `YYYY-MM-DD[THH:MM:SS[.fff]][Z|±hh:mm]`
/// shapes the backend's `Date.parse` accepts.
fn try_parse_date(s: &str) -> Option<i64> {
    let b = s.as_bytes();
    // Regex guard: ^\d{4}-\d{2}-\d{2}
    if b.len() < 10 {
        return None;
    }
    let is_d = |i: usize| b[i].is_ascii_digit();
    if !(is_d(0) && is_d(1) && is_d(2) && is_d(3) && b[4] == b'-' && is_d(5) && is_d(6) && b[7] == b'-' && is_d(8) && is_d(9))
    {
        return None;
    }
    let year: i64 = s[0..4].parse().ok()?;
    let month: i64 = s[5..7].parse().ok()?;
    let day: i64 = s[8..10].parse().ok()?;
    if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
        return None;
    }

    // Optional time component: T or space, then HH:MM[:SS[.fff]] and optional zone.
    let mut hour: i64 = 0;
    let mut min: i64 = 0;
    let mut sec: i64 = 0;
    let mut millis: i64 = 0;
    let mut tz_offset_min: i64 = 0; // applied as: utc = local - offset

    let rest = &s[10..];
    if !rest.is_empty() {
        let rb = rest.as_bytes();
        if rb[0] != b'T' && rb[0] != b' ' {
            return None;
        }
        let time = &rest[1..];
        // Split off timezone designator.
        let (clock, tz) = split_timezone(time);
        let parts: Vec<&str> = clock.split(':').collect();
        if parts.len() < 2 {
            return None;
        }
        hour = parts[0].parse().ok()?;
        min = parts[1].parse().ok()?;
        if parts.len() >= 3 {
            let secpart = parts[2];
            if let Some(dot) = secpart.find('.') {
                sec = secpart[..dot].parse().ok()?;
                let frac = &secpart[dot + 1..];
                let frac3: String = frac.chars().take(3).chain(std::iter::repeat('0')).take(3).collect();
                millis = frac3.parse().ok()?;
            } else {
                sec = secpart.parse().ok()?;
            }
        }
        if let Some(off) = tz {
            tz_offset_min = off?;
        }
    }

    // Days from civil (Howard Hinnant's algorithm) → days since 1970-01-01.
    let days = days_from_civil(year, month, day);
    let total_secs = days * 86_400 + hour * 3600 + min * 60 + sec - tz_offset_min * 60;
    Some(total_secs * 1000 + millis)
}

/// Returns (clock_part, optional timezone). The Option<Option<i64>> inner:
/// `None` = no tz, `Some(Some(min))` = parsed offset, `Some(None)` = malformed.
fn split_timezone(time: &str) -> (&str, Option<Option<i64>>) {
    if let Some(stripped) = time.strip_suffix('Z') {
        return (stripped, Some(Some(0)));
    }
    // Look for +hh:mm or -hh:mm after the time (not the date — already stripped).
    for (i, c) in time.char_indices() {
        if (c == '+' || c == '-') && i > 0 {
            let clock = &time[..i];
            let sign = if c == '-' { -1 } else { 1 };
            let off = &time[i + 1..];
            let parsed = parse_offset(off).map(|m| sign * m);
            return (clock, Some(parsed));
        }
    }
    (time, None)
}

fn parse_offset(off: &str) -> Option<i64> {
    let parts: Vec<&str> = off.split(':').collect();
    let h: i64 = parts.first()?.parse().ok()?;
    let m: i64 = parts.get(1).map(|s| s.parse().ok()).unwrap_or(Some(0))?;
    Some(h * 60 + m)
}

/// Days since 1970-01-01 for a proleptic Gregorian (y, m, d). Hinnant 2013.
fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400; // [0, 399]
    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1; // [0, 365]
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
    era * 146_097 + doe - 719_468
}

#[cfg(test)]
mod tests {
    use super::matches_rule;
    use crate::types::{Operator, TargetingRule};
    use serde_json::{json, Value};

    fn rule(op: Operator, expected: Value) -> TargetingRule {
        TargetingRule {
            attribute: "attr".to_string(),
            operator: op,
            value: expected,
        }
    }

    /// Asserts ALL canonical cross-language vectors from
    /// `scratch/sdk-operator-parity-spec.md` (§ Canonical test vectors).
    /// `actual` is `None` to model an absent attribute (the `null` row).
    #[test]
    fn canonical_operator_parity_vectors() {
        let s = |v: &str| Value::String(v.to_string());
        // (operator, actual, expected, want)
        let cases: Vec<(Operator, Option<Value>, Value, bool)> = vec![
            (Operator::Exists, Some(s("x")), Value::Null, true),
            (Operator::Exists, Some(s("")), Value::Null, false),
            (Operator::NotExists, None, Value::Null, true),
            (Operator::Equals, Some(s("5")), s("5"), true),
            (Operator::Is, Some(s("5")), s("5"), true),
            (Operator::NotEquals, Some(s("5")), s("6"), true),
            (Operator::IsNot, Some(s("a")), s("a"), false),
            (Operator::AnyOf, Some(s("b")), json!(["a", "b", "c"]), true),
            (Operator::AnyOf, Some(s("z")), json!(["a", "b", "c"]), false),
            (Operator::NotAnyOf, Some(s("z")), json!(["a", "b", "c"]), true),
            (Operator::Contains, Some(s("hello")), s("ell"), true),
            (Operator::NotContains, Some(s("hello")), s("xyz"), true),
            (Operator::GreaterThan, Some(s("10")), s("5"), true),
            (Operator::Gt, Some(s("3")), s("5"), false),
            (Operator::LessThan, Some(s("3")), s("5"), true),
            (Operator::Gte, Some(s("5")), s("5"), true),
            (Operator::Lte, Some(s("5")), s("5"), true),
            (Operator::GreaterThan, Some(s("2026-02-01")), s("2026-01-01"), true),
            (Operator::LessThan, Some(s("2026-01-01")), s("2026-02-01"), true),
            (Operator::Gte, Some(s("2026-01-01")), s("2026-01-01"), true),
        ];

        for (i, (op, actual, expected, want)) in cases.into_iter().enumerate() {
            let r = rule(op.clone(), expected.clone());
            let got = matches_rule(&r, actual.as_ref());
            assert_eq!(
                got, want,
                "vector #{i}: op={op:?} actual={actual:?} expected={expected:?} => got {got}, want {want}"
            );
        }
    }

    #[test]
    fn date_compare_with_time_and_zone() {
        let s = |v: &str| Value::String(v.to_string());
        // Same instant expressed via Z vs +00:00.
        let r = rule(Operator::GreaterThan, s("2026-01-01T00:00:00+01:00"));
        assert!(matches_rule(&r, Some(&s("2026-01-01T00:00:00Z")))); // 00:00Z > 23:00 prev day UTC
        let r = rule(Operator::LessThanOrEqual, s("2026-01-01T12:00:00.500Z"));
        assert!(matches_rule(&r, Some(&s("2026-01-01T12:00:00.499Z"))));
    }

    #[test]
    fn plain_number_not_treated_as_date() {
        let s = |v: &str| Value::String(v.to_string());
        // "10" must NOT be a date; numeric path: 10 > 5.
        let r = rule(Operator::GreaterThan, s("5"));
        assert!(matches_rule(&r, Some(&s("10"))));
    }
}