relate-planner 1.5.0

Bind OpenCypher AST to a logical plan
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
//! The statically-known literal vocabulary: what an expression spells when
//! its value is known at plan time (a literal, a resolved plan-cache
//! placeholder, a folded eager value), the ADR-0175 rejections the
//! integer-argument sites raise from it, and the `CALL { … } IN
//! TRANSACTIONS` modifier sites' one numeric-literal gate
//! ([`check_modifier_literal`]), run under two policy rows: the positive
//! integer gate (batch size, concurrency hint) and the non-negative
//! duration gate (retry duration) — whose texts and class mapping live in
//! the `relate_core::integer_args` rows, REL8-2179. A crate-level module,
//! below both the expression checker and the binding classifier that read it, so
//! neither imports back up into the other.

use relate_core::integer_args::{self, range_text, IntegerArgSite};
use relate_core::{invalid_argument_text, number_out_of_range_text, Error, Result, Value};
use relate_ir::{Expr, UnaryOp};

/// The literal an expression spells, bucketed by the kind each caller
/// tests for — `Other` carries every value that is none of the named kinds.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum LiteralKind {
    Null,
    Bool,
    Int,
    Float,
    /// A list literal, whatever its elements' dynamism.
    List,
    /// A map literal, whatever its values' dynamism.
    Map,
    /// Every other value: string, temporal, entity, …
    Other,
}

/// The statically-known literal an expression spells, as the value itself: a
/// plan-cache placeholder is resolved to the literal it replaced (ADR-0503),
/// a unary sign is unwrapped (the parser splits `-1.5` and `+1.5` into a
/// unary operator over the literal), and list/map literals fold to their
/// values. A caller's own parameter and every non-literal expression are
/// `None`. The one `Expr → Option<Value>` walk of this vocabulary;
/// [`static_literal`] classifies its result.
pub(crate) fn static_arg_value(expr: &Expr) -> Option<Value> {
    match expr {
        Expr::Null => Some(Value::Null),
        Expr::Bool(value) => Some(Value::Bool(*value)),
        Expr::Int(value) => Some(Value::Int(*value)),
        Expr::Float(value) => Some(Value::Float(*value)),
        Expr::String(value) => Some(Value::String(value.as_str().into())),
        // An executor-side eager value: a temporal constructor call the
        // front end folded (`date('2020-01-01')`).
        Expr::RuntimeValue(value) => Some(value.clone()),
        Expr::Parameter(name) => relate_core::auto_literal(name),
        Expr::List(items) => Value::checked_list(
            items
                .iter()
                .map(static_arg_value)
                .collect::<Option<Vec<_>>>()?,
        )
        .ok(),
        Expr::Map(pairs) => {
            let map = pairs
                .iter()
                .map(|(key, value)| Some((key.clone(), static_arg_value(value)?)))
                .collect::<Option<std::collections::BTreeMap<_, _>>>()?;
            Value::checked_map(map).ok()
        }
        Expr::Unary {
            op: UnaryOp::Plus,
            expr,
        } => static_arg_value(expr),
        Expr::Unary {
            op: UnaryOp::Minus,
            expr,
        } => match static_arg_value(expr)? {
            Value::Int(value) => value.checked_neg().map(Value::Int),
            Value::Float(value) => Some(Value::Float(-value)),
            _ => None,
        },
        _ => None,
    }
}

/// The literal an expression spells, bucketed by the kind each caller tests
/// for. A collection literal is `List`/`Map` even when an element is dynamic:
/// the kind a site tests for is the collection. A sign is transparent
/// whatever its operand's kind (a nonsense `-'x'` is still a non-numeric
/// literal). The one classification of this vocabulary, shared by the
/// argument-type rules and [`crate::binding::Binding::of_static_expr`].
pub(crate) fn static_literal(expr: &Expr) -> Option<LiteralKind> {
    match expr {
        Expr::List(_) => Some(LiteralKind::List),
        Expr::Map(_) => Some(LiteralKind::Map),
        Expr::Unary {
            op: UnaryOp::Minus | UnaryOp::Plus,
            expr,
        } => static_literal(expr),
        other => static_arg_value(other).map(|value| literal_kind(&value)),
    }
}

fn literal_kind(value: &Value) -> LiteralKind {
    match value {
        Value::Null => LiteralKind::Null,
        Value::Bool(_) => LiteralKind::Bool,
        Value::Int(_) => LiteralKind::Int,
        Value::Float(_) => LiteralKind::Float,
        Value::List(_) => LiteralKind::List,
        Value::Map(_) => LiteralKind::Map,
        // Every other value is a non-numeric literal; an unknown one is
        // rejected at an integer-argument site (it fails closed).
        Value::String(_)
        | Value::Node(_)
        | Value::Relationship(_)
        | Value::Path(_)
        | Value::Temporal(_)
        | Value::Point(_)
        | Value::Uuid(_)
        | Value::Vector { .. }
        | Value::Bytes(_) => LiteralKind::Other,
    }
}

pub(crate) fn is_static_non_bool(expr: &Expr) -> bool {
    // Bool and null stay legal boolean operands.
    matches!(expr, Expr::CountStar)
        || matches!(
            static_literal(expr),
            Some(kind) if !matches!(kind, LiteralKind::Bool | LiteralKind::Null)
        )
}

/// Whether `expr` is a float literal, including a plan-cache placeholder
/// for one.
fn is_float_literal(expr: &Expr) -> bool {
    static_literal(expr) == Some(LiteralKind::Float)
}

/// ADR-0175 (statically-known floats): the integer-argument site an
/// expression carries whose literal gate is a float — a list index or a
/// slice bound — paired with the site whose authored detail a rejection
/// names. The one list of those forms, precedence included (a slice's
/// start before its end): the checker rejects through it and the
/// plan-cache walk classifies through it.
///
/// A float *literal*, sign included: the parser splits `-1.5`/`+1.5`
/// into a unary sign over the literal, and both spellings are the mistake
/// Neo4j's static FLOAT gate rejects at compile time (22N27 / 22NB1).
/// Constant float *expressions* (`0.0/0.0`, `head([1.0, 'x'])`, …) are
/// not literals and are handled at runtime, and the two sites differ
/// there: a list index rejects every float at runtime with the same text
/// this gate raises, while a slice bound's wording is plan-time-only — its
/// runtime coercion truncates floats (NaN → 0) and saturates into the
/// int32 range, never a range fault (ADR-0631).
pub(crate) fn float_integer_site(expr: &Expr) -> Option<&'static IntegerArgSite> {
    match expr {
        Expr::Subscript { index, .. } if is_float_literal(index) => Some(&integer_args::LIST_INDEX),
        Expr::Slice { start, .. } if start.as_deref().is_some_and(is_float_literal) => {
            Some(&integer_args::SLICE_START)
        }
        Expr::Slice { end, .. } if end.as_deref().is_some_and(is_float_literal) => {
            Some(&integer_args::SLICE_END)
        }
        _ => None,
    }
}

/// ADR-0175: reject a float literal at the integer site `expr` carries,
/// naming that site's authored detail ([`float_integer_site`] owns the
/// list).
pub(crate) fn reject_float_integer_site(expr: &Expr) -> Result<()> {
    match float_integer_site(expr) {
        Some(site) => Err(Error::invalid_argument_type(site.type_error)),
        None => Ok(()),
    }
}

/// Whether `expr` is a statically-known literal of a type that is not
/// INTEGER. Live Neo4j 2026.10.1 reports the integer-argument sites'
/// wrong-typed literals as type mismatches (`substring('abcdef','x')`,
/// `substring('abcdef',1,'x')`, `left('abcdef','x')`,
/// `right('abcdef','x')`, `range('a',5)`, and a temporal constructor call
/// such as `substring('abcdef', date('2020-01-01'))`, which the front end
/// folds to a `RuntimeValue`). `null` is legal (it nulls the call), an
/// integer literal stays, and a constant expression whose type is only
/// known at runtime (`head(['x','1'])`) is handled by the executor's own
/// rejection.
pub(crate) fn is_non_integer_literal(expr: &Expr) -> bool {
    matches!(
        static_literal(expr),
        Some(kind) if !matches!(kind, LiteralKind::Int | LiteralKind::Null)
    )
}

/// ADR-0175: reject a non-INTEGER literal at an integer-argument site
/// with the site's authored `InvalidArgumentType` detail — the plan-time
/// half of the type rejection whose runtime half is the executor's own
/// argument coercion.
pub(crate) fn reject_non_integer_literal(expr: &Expr, detail: &str) -> Result<()> {
    if is_non_integer_literal(expr) {
        return Err(Error::invalid_argument_type(detail));
    }
    Ok(())
}

/// A `CALL { … } IN TRANSACTIONS` modifier site's numeric-literal policy,
/// carried as data: the literal kinds its type sentence accepts, the
/// smallest numeric value in range, whether a unary-minus spelling is
/// out of range outright, and the token its range sentence travels under.
/// The two rows below are the only policies (REL8-2179).
#[derive(Clone, Copy)]
pub(crate) struct ModifierGate {
    accepts: &'static [LiteralKind],
    min: f64,
    any_minus_out_of_range: bool,
    range_text: fn(&'static str) -> String,
}

impl ModifierGate {
    /// The batch size and concurrency hint: INTEGER only (`null` legal),
    /// zero and negatives out of range, token `InvalidArgument`.
    pub(crate) const POSITIVE: Self = Self {
        accepts: &[LiteralKind::Int, LiteralKind::Null],
        min: 1.0,
        any_minus_out_of_range: false,
        range_text: |detail| invalid_argument_text(detail),
    };
    /// The retry duration: INTEGER or FLOAT, any negative (or
    /// unary-minus spelled) literal out of range, token `NumberOutOfRange`;
    /// `null` and every non-numeric kind is a type error.
    pub(crate) const NON_NEGATIVE: Self = Self {
        accepts: &[LiteralKind::Int, LiteralKind::Float],
        min: 0.0,
        any_minus_out_of_range: true,
        range_text: |detail| number_out_of_range_text(detail),
    };

    /// The one range rule: a number below `min` is out of range when its
    /// kind is accepted, or when a FLOAT is written negative (a negative
    /// float at an INTEGER-only site is a range fault, a positive one a
    /// type fault). The value comes from [`static_arg_value`], the one
    /// sign-unwrapping walk, so a resolved plan-cache placeholder reads
    /// like the literal it replaced.
    fn out_of_range(&self, expr: &Expr) -> bool {
        if self.any_minus_out_of_range
            && matches!(
                expr,
                Expr::Unary {
                    op: UnaryOp::Minus,
                    ..
                }
            )
        {
            return true;
        }
        let (number, kind) = match static_arg_value(expr) {
            Some(Value::Int(value)) => (value as f64, LiteralKind::Int),
            Some(Value::Float(value)) => (value, LiteralKind::Float),
            _ => return false,
        };
        number < self.min && (self.accepts.contains(&kind) || number.is_sign_negative())
    }

    fn rejects_type(&self, expr: &Expr) -> bool {
        static_literal(expr).is_some_and(|kind| !self.accepts.contains(&kind))
    }
}

/// The `CALL { … } IN TRANSACTIONS` modifier sites' one numeric-literal
/// gate (batch size, concurrency hint, retry duration): an out-of-range
/// literal rejects with the site's range sentence under the gate's token,
/// a wrong-kind literal with its type sentence, both in the `Syntax` class
/// — the plan-time half of the runtime coercion whose texts the site's row
/// owns. Anything not statically known passes (the runtime owns it).
pub(crate) fn check_modifier_literal(
    expr: &Expr,
    site: &IntegerArgSite,
    gate: ModifierGate,
) -> Result<()> {
    if gate.out_of_range(expr) {
        return Err(Error::syntax((gate.range_text)(range_text(site))));
    }
    if gate.rejects_type(expr) {
        return Err(Error::invalid_argument_type(site.type_error).into_syntax());
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use relate_core::integer_args::{TX_BATCH_SIZE, TX_RETRY_DURATION};

    fn neg(expr: Expr) -> Expr {
        Expr::Unary {
            op: UnaryOp::Minus,
            expr: Box::new(expr),
        }
    }

    fn rejection(result: Result<()>) -> String {
        result.expect_err("the literal is rejected").to_string()
    }

    #[test]
    fn the_positive_gate_rejects_every_non_positive_spelling_through_one_walk() {
        for expr in [
            Expr::Int(0),
            Expr::Int(-1),
            neg(Expr::Int(1)),
            neg(Expr::Float(1.5)),
        ] {
            let text = rejection(check_modifier_literal(
                &expr,
                &TX_BATCH_SIZE,
                ModifierGate::POSITIVE,
            ));
            assert!(
                text.contains("InvalidArgument: batch size must be a positive integer"),
                "{text}"
            );
        }
        check_modifier_literal(&Expr::Int(3), &TX_BATCH_SIZE, ModifierGate::POSITIVE)
            .expect("positive passes");
        let text = rejection(check_modifier_literal(
            &Expr::Float(1.5),
            &TX_BATCH_SIZE,
            ModifierGate::POSITIVE,
        ));
        assert!(text.contains("batch size must be an integer"), "{text}");
    }

    #[test]
    fn the_duration_gate_splits_range_from_type_in_one_match() {
        for expr in [
            neg(Expr::Int(0)),
            neg(Expr::Int(1)),
            neg(Expr::Float(0.5)),
            Expr::Int(-2),
        ] {
            let text = rejection(check_modifier_literal(
                &expr,
                &TX_RETRY_DURATION,
                ModifierGate::NON_NEGATIVE,
            ));
            assert!(
                text.contains("NumberOutOfRange: retry duration must be non-negative"),
                "{text}"
            );
        }
        for expr in [
            Expr::Null,
            Expr::Bool(true),
            Expr::String("x".into()),
            Expr::List(vec![]),
            Expr::Map(vec![]),
        ] {
            let text = rejection(check_modifier_literal(
                &expr,
                &TX_RETRY_DURATION,
                ModifierGate::NON_NEGATIVE,
            ));
            assert!(text.contains("retry duration must be numeric"), "{text}");
        }
        for expr in [Expr::Int(0), Expr::Float(2.5)] {
            check_modifier_literal(&expr, &TX_RETRY_DURATION, ModifierGate::NON_NEGATIVE)
                .expect("non-negative passes");
        }
    }

    #[test]
    fn a_resolved_plan_cache_placeholder_reads_like_the_literal_it_replaced() {
        use relate_core::AutoLiteralGuard;
        use std::collections::BTreeMap;

        let params = BTreeMap::from([
            ("__AUTO_0__".to_string(), Value::Int(-4)),
            ("__AUTO_1__".to_string(), Value::Int(7)),
        ]);
        let _guard = AutoLiteralGuard::install(&params);
        let placeholder = |name: &str| Expr::Parameter(name.to_string());

        let text = rejection(check_modifier_literal(
            &placeholder("__AUTO_0__"),
            &TX_RETRY_DURATION,
            ModifierGate::NON_NEGATIVE,
        ));
        assert!(
            text.contains("NumberOutOfRange: retry duration must be non-negative"),
            "{text}"
        );
        let text = rejection(check_modifier_literal(
            &placeholder("__AUTO_0__"),
            &TX_BATCH_SIZE,
            ModifierGate::POSITIVE,
        ));
        assert!(
            text.contains("InvalidArgument: batch size must be a positive integer"),
            "{text}"
        );
        for gate in [ModifierGate::POSITIVE, ModifierGate::NON_NEGATIVE] {
            check_modifier_literal(&placeholder("__AUTO_1__"), &TX_BATCH_SIZE, gate)
                .expect("a valid placeholder passes");
        }
        // A caller's own parameter is runtime-typed: never rejected here.
        check_modifier_literal(&placeholder("n"), &TX_BATCH_SIZE, ModifierGate::POSITIVE)
            .expect("a caller parameter passes");
    }
}