reddb-io-server 1.1.0

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
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
//! Parser hardening test suite for the Graph DSL (issue #99).
//!
//! Reuses the `tests/support/parser_hardening` harness from #87 to
//! cover the `MATCH` pattern surface, multi-hop pattern paths, the
//! optional `WHERE` slot inside `MATCH`, the `PATH FROM ... TO ...`
//! query, and the `GRAPH ...` traversal commands. The Graph DSL is
//! reached through the same `parser::parse` entry point as SQL —
//! `MATCH` / `PATH` / `GRAPH` are dispatched in
//! `parse_frontend_statement` — so `ParserLimits` cascade
//! automatically. This file pins the contract.
//!
//! Phase A constraint (issue #99): tests-only. If a property test
//! flushes out a parser bug, pin the broken behaviour with a
//! `// FIXME:` comment and file a follow-up — do *not* modify
//! `lexer.rs` / `parser/` to "fix" it from inside this PR.

mod support {
    pub mod parser_hardening;
}

use proptest::prelude::*;
use reddb_server::storage::query::parser::{self, ParseError, ParserLimits};
use support::parser_hardening::{
    self as harness, assert_no_panic_on, corpus::graph_dsl_adversarial_inputs, graph_dsl_grammar,
    HardenedParser,
};

/// `HardenedParser` shim around the Graph DSL surface. The graph
/// parser shares the top-level entry point with the rest of the
/// SQL-flavoured grammar, so the shim simply funnels into
/// `parser::parse` — what makes this distinct from the SQL shim is
/// the property + snapshot suites below, which only feed graph-
/// shaped inputs.
pub struct GraphDslParser;

impl HardenedParser for GraphDslParser {
    type Error = ParseError;

    fn parse(input: &str) -> Result<(), Self::Error> {
        parser::parse(input).map(|_| ())
    }

    fn parse_with_limits(input: &str, limits: ParserLimits) -> Result<(), Self::Error> {
        let mut p = parser::Parser::with_limits(input, limits)?;
        p.parse().map(|_| ())
    }
}

// ---- panic-safety on adversarial corpus -------------------------

#[test]
fn graph_dsl_parser_does_not_panic_on_adversarial_corpus() {
    let handle = std::thread::Builder::new()
        .stack_size(8 * 1024 * 1024)
        .spawn(|| {
            for (name, input) in graph_dsl_adversarial_inputs() {
                let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    assert_no_panic_on::<GraphDslParser>(&input);
                }));
                if result.is_err() {
                    panic!("graph DSL adversarial corpus entry {} panicked", name);
                }
            }
        })
        .expect("spawn corpus thread");
    handle.join().expect("corpus thread panic");
}

// ---- property tests ---------------------------------------------

proptest! {
    #![proptest_config(ProptestConfig {
        cases: 256,
        max_shrink_iters: 64,
        ..ProptestConfig::default()
    })]

    /// Generated single-hop `MATCH (a)-[r]->(b) RETURN a` shapes
    /// parse cleanly.
    #[test]
    fn proptest_match_simple_roundtrips(s in graph_dsl_grammar::match_simple_stmt()) {
        harness::roundtrip_property::<GraphDslParser>(&s);
        prop_assert!(
            GraphDslParser::parse(&s).is_ok(),
            "match simple did not parse: {}", s
        );
    }

    /// Generated multi-hop pattern paths
    /// `(a)-[]->(b)-[]->(c)…` parse cleanly.
    #[test]
    fn proptest_match_pattern_path_roundtrips(
        s in graph_dsl_grammar::match_pattern_path_stmt(),
    ) {
        harness::roundtrip_property::<GraphDslParser>(&s);
        prop_assert!(
            GraphDslParser::parse(&s).is_ok(),
            "match pattern path did not parse: {}", s
        );
    }

    /// Generated `MATCH … WHERE … RETURN …` shapes parse cleanly.
    #[test]
    fn proptest_match_with_where_roundtrips(
        s in graph_dsl_grammar::match_with_where_stmt(),
    ) {
        harness::roundtrip_property::<GraphDslParser>(&s);
        prop_assert!(
            GraphDslParser::parse(&s).is_ok(),
            "match with where did not parse: {}", s
        );
    }

    /// Generated `PATH FROM host('x') TO host('y') …` shapes parse
    /// cleanly.
    #[test]
    fn proptest_path_query_roundtrips(s in graph_dsl_grammar::path_query_stmt()) {
        harness::roundtrip_property::<GraphDslParser>(&s);
        prop_assert!(
            GraphDslParser::parse(&s).is_ok(),
            "path query did not parse: {}", s
        );
    }

    /// Generated `GRAPH NEIGHBORHOOD/TRAVERSE/SHORTEST_PATH/CENTRALITY`
    /// shapes parse cleanly.
    #[test]
    fn proptest_graph_traversal_roundtrips(
        s in graph_dsl_grammar::graph_traversal_stmt(),
    ) {
        harness::roundtrip_property::<GraphDslParser>(&s);
        prop_assert!(
            GraphDslParser::parse(&s).is_ok(),
            "graph traversal did not parse: {}", s
        );
    }

    /// Arbitrary bytes prefixed with a graph DSL keyword never panic.
    /// `Err` is the expected outcome; only an unwind panic is a
    /// regression.
    #[test]
    fn proptest_graph_arbitrary_suffix_no_panic(
        prefix in prop_oneof![
            Just("MATCH ".to_string()),
            Just("PATH ".to_string()),
            Just("GRAPH ".to_string()),
        ],
        suffix in ".{0,512}",
    ) {
        let s = format!("{}{}", prefix, suffix);
        harness::roundtrip_property::<GraphDslParser>(&s);
    }

    /// `CREATE NODE …` shapes are not part of the SQL-side graph
    /// grammar (the operation lives behind API entry points). The
    /// parser must Err but never panic.
    #[test]
    fn proptest_create_node_attempt_no_panic(
        s in graph_dsl_grammar::create_node_attempt_stmt(),
    ) {
        harness::roundtrip_property::<GraphDslParser>(&s);
    }

    /// `CREATE EDGE …` shapes are not part of the SQL-side graph
    /// grammar — same caveat as `CREATE NODE`. Must Err, must not
    /// panic.
    #[test]
    fn proptest_create_edge_attempt_no_panic(
        s in graph_dsl_grammar::create_edge_attempt_stmt(),
    ) {
        harness::roundtrip_property::<GraphDslParser>(&s);
    }

    /// Tighter limits always refuse oversized graph DSL inputs.
    #[test]
    fn proptest_graph_input_size_limit_enforced(len in 200usize..2000) {
        let limits = ParserLimits {
            max_input_bytes: 64,
            ..ParserLimits::default()
        };
        let body = "x".repeat(len);
        let input = format!("MATCH (a) RETURN {}", body);
        let r = GraphDslParser::parse_with_limits(&input, limits);
        prop_assert!(r.is_err(), "oversized graph input must error");
    }
}

// ---- happy-path regression tests --------------------------------
//
// Each test below pins a concrete user-visible Graph DSL shape so
// future grammar tweaks that silently break a documented example
// surface as a test failure (with the exact AST shape printed),
// not a runtime regression three layers deep.

use reddb_server::storage::query::ast::{
    EdgeDirection, GraphCommand, GraphCommandOrderBy, NodeSelector, QueryExpr,
};

fn parse_query(input: &str) -> QueryExpr {
    parser::parse(input)
        .unwrap_or_else(|e| panic!("expected ok for {input:?}, got error: {e}"))
        .query
}

#[test]
fn match_single_hop_outgoing_parses() {
    let q = parse_query("MATCH (a:person)-[r:KNOWS]->(b:person) RETURN a, b");
    match q {
        QueryExpr::Graph(g) => {
            assert_eq!(g.pattern.nodes.len(), 2);
            assert_eq!(g.pattern.edges.len(), 1);
            assert_eq!(g.pattern.nodes[0].alias, "a");
            assert_eq!(g.pattern.nodes[0].node_label.as_deref(), Some("person"));
            assert_eq!(g.pattern.edges[0].direction, EdgeDirection::Outgoing);
            assert_eq!(g.pattern.edges[0].edge_label.as_deref(), Some("knows"));
            assert_eq!(g.return_.len(), 2);
        }
        other => panic!("expected Graph, got {other:?}"),
    }
}

#[test]
fn match_incoming_edge_parses() {
    let q = parse_query("MATCH (a)<-[r:FOLLOWS]-(b:person) RETURN b");
    match q {
        QueryExpr::Graph(g) => {
            assert_eq!(g.pattern.edges.len(), 1);
            assert_eq!(g.pattern.edges[0].direction, EdgeDirection::Incoming);
        }
        other => panic!("expected Graph, got {other:?}"),
    }
}

#[test]
fn match_multi_hop_pattern_path_parses() {
    let q = parse_query(
        "MATCH (a:person)-[:WORKS_AT]->(c:company)-[:LOCATED_IN]->(city) RETURN a, c, city",
    );
    match q {
        QueryExpr::Graph(g) => {
            assert_eq!(g.pattern.nodes.len(), 3);
            assert_eq!(g.pattern.edges.len(), 2);
            assert_eq!(g.return_.len(), 3);
        }
        other => panic!("expected Graph, got {other:?}"),
    }
}

#[test]
fn match_with_where_clause_parses() {
    let q = parse_query(
        "MATCH (a:person)-[r:COLLABORATES]->(b:person) WHERE a.department = 'engineering' \
         RETURN a, b",
    );
    match q {
        QueryExpr::Graph(g) => {
            assert!(g.filter.is_some(), "WHERE filter must be present");
            assert_eq!(
                g.pattern.edges[0].edge_label.as_deref(),
                Some("collaborates")
            );
        }
        other => panic!("expected Graph, got {other:?}"),
    }
}

#[test]
fn match_with_property_filter_parses() {
    let q = parse_query("MATCH (a:person {name: 'alice'}) RETURN a");
    match q {
        QueryExpr::Graph(g) => {
            assert_eq!(g.pattern.nodes[0].properties.len(), 1);
            assert_eq!(g.pattern.nodes[0].properties[0].name, "name");
        }
        other => panic!("expected Graph, got {other:?}"),
    }
}

#[test]
fn match_with_variable_length_edge_parses() {
    let q = parse_query("MATCH (a:person)-[r*1..3]->(b:person) RETURN a, b");
    match q {
        QueryExpr::Graph(g) => {
            assert_eq!(g.pattern.edges[0].min_hops, 1);
            assert_eq!(g.pattern.edges[0].max_hops, 3);
        }
        other => panic!("expected Graph, got {other:?}"),
    }
}

#[test]
fn graph_neighborhood_command_parses() {
    let q = parse_query("GRAPH NEIGHBORHOOD 'alice' DEPTH 2 DIRECTION outgoing");
    match q {
        QueryExpr::GraphCommand(GraphCommand::Neighborhood {
            source,
            depth,
            direction,
            edge_labels,
        }) => {
            assert_eq!(source, "alice");
            assert_eq!(depth, 2);
            assert_eq!(direction, "outgoing");
            assert_eq!(edge_labels, None);
        }
        other => panic!("expected Neighborhood, got {other:?}"),
    }
}

#[test]
fn graph_neighborhood_edges_in_filter_parses() {
    let q = parse_query("GRAPH NEIGHBORHOOD 'alice' EDGES IN ('EATS', 'KILLS') DEPTH 2");
    match q {
        QueryExpr::GraphCommand(GraphCommand::Neighborhood {
            source,
            depth,
            edge_labels,
            ..
        }) => {
            assert_eq!(source, "alice");
            assert_eq!(depth, 2);
            assert_eq!(
                edge_labels,
                Some(vec!["EATS".to_string(), "KILLS".to_string()])
            );
        }
        other => panic!("expected Neighborhood, got {other:?}"),
    }
}

#[test]
fn graph_shortest_path_command_parses() {
    let q = parse_query("GRAPH SHORTEST_PATH 'alice' TO 'bob' ALGORITHM dijkstra");
    match q {
        QueryExpr::GraphCommand(GraphCommand::ShortestPath {
            source,
            target,
            algorithm,
            ..
        }) => {
            assert_eq!(source, "alice");
            assert_eq!(target, "bob");
            assert_eq!(algorithm, "dijkstra");
        }
        other => panic!("expected ShortestPath, got {other:?}"),
    }
}

#[test]
fn graph_traverse_command_parses() {
    let q = parse_query("GRAPH TRAVERSE 'alice' STRATEGY bfs DEPTH 3");
    match q {
        QueryExpr::GraphCommand(GraphCommand::Traverse {
            source,
            strategy,
            depth,
            edge_labels,
            ..
        }) => {
            assert_eq!(source, "alice");
            assert_eq!(strategy, "bfs");
            assert_eq!(depth, 3);
            assert_eq!(edge_labels, None);
        }
        other => panic!("expected Traverse, got {other:?}"),
    }
}

#[test]
fn graph_traverse_edges_in_filter_parses() {
    let q = parse_query("GRAPH TRAVERSE FROM 'alice' STRATEGY bfs EDGES IN ('EATS') MAX_DEPTH 3");
    match q {
        QueryExpr::GraphCommand(GraphCommand::Traverse {
            source,
            strategy,
            depth,
            edge_labels,
            ..
        }) => {
            assert_eq!(source, "alice");
            assert_eq!(strategy, "bfs");
            assert_eq!(depth, 3);
            assert_eq!(edge_labels, Some(vec!["EATS".to_string()]));
        }
        other => panic!("expected Traverse, got {other:?}"),
    }
}

// Issue #417: docs↔parser drift — documented `GRAPH TRAVERSE FROM '<id>'
// STRATEGY bfs MAX_DEPTH n` form must parse identically to the bare form.
#[test]
fn graph_traverse_from_strategy_max_depth_form_parses() {
    let q = parse_query("GRAPH TRAVERSE FROM 'alice' STRATEGY bfs DIRECTION outgoing MAX_DEPTH 3");
    match q {
        QueryExpr::GraphCommand(GraphCommand::Traverse {
            source,
            strategy,
            depth,
            direction,
            ..
        }) => {
            assert_eq!(source, "alice");
            assert_eq!(strategy, "bfs");
            assert_eq!(depth, 3);
            assert_eq!(direction, "outgoing");
        }
        other => panic!("expected Traverse, got {other:?}"),
    }
}

#[test]
fn graph_shortest_path_from_to_form_parses() {
    let q = parse_query("GRAPH SHORTEST_PATH FROM 'a' TO 'b' ALGORITHM dijkstra");
    match q {
        QueryExpr::GraphCommand(GraphCommand::ShortestPath {
            source,
            target,
            algorithm,
            ..
        }) => {
            assert_eq!(source, "a");
            assert_eq!(target, "b");
            assert_eq!(algorithm, "dijkstra");
        }
        other => panic!("expected ShortestPath, got {other:?}"),
    }
}

#[test]
fn graph_shortest_path_limit_parses() {
    let q = parse_query("GRAPH SHORTEST_PATH FROM 'a' TO 'b' LIMIT 0");
    match q {
        QueryExpr::GraphCommand(GraphCommand::ShortestPath {
            source,
            target,
            limit,
            ..
        }) => {
            assert_eq!(source, "a");
            assert_eq!(target, "b");
            assert_eq!(limit, Some(0));
        }
        other => panic!("expected ShortestPath, got {other:?}"),
    }
}

#[test]
fn graph_components_limit_parses() {
    let q = parse_query("GRAPH COMPONENTS MODE weak LIMIT 2");
    match q {
        QueryExpr::GraphCommand(GraphCommand::Components {
            mode,
            limit,
            order_by,
        }) => {
            assert_eq!(mode, "weak");
            assert_eq!(limit, Some(2));
            assert!(order_by.is_none());
        }
        other => panic!("expected Components, got {other:?}"),
    }
}

#[test]
fn graph_community_order_by_size_limit_parses() {
    let q = parse_query("GRAPH COMMUNITY ALGORITHM louvain ORDER BY size DESC LIMIT 5");
    match q {
        QueryExpr::GraphCommand(GraphCommand::Community {
            algorithm,
            max_iterations,
            limit,
            order_by: Some(GraphCommandOrderBy { metric, ascending }),
        }) => {
            assert_eq!(algorithm, "louvain");
            assert_eq!(max_iterations, 100);
            assert_eq!(metric, "size");
            assert!(!ascending);
            assert_eq!(limit, Some(5));
        }
        other => panic!("expected Community with ORDER BY size DESC LIMIT 5, got {other:?}"),
    }
}

#[test]
fn graph_components_order_by_component_size_asc_limit_parses() {
    let q = parse_query("GRAPH COMPONENTS MODE weak ORDER BY component_size ASC LIMIT 2");
    match q {
        QueryExpr::GraphCommand(GraphCommand::Components {
            mode,
            limit,
            order_by: Some(GraphCommandOrderBy { metric, ascending }),
        }) => {
            assert_eq!(mode, "weak");
            assert_eq!(metric, "component_size");
            assert!(ascending);
            assert_eq!(limit, Some(2));
        }
        other => {
            panic!("expected Components with ORDER BY component_size ASC LIMIT 2, got {other:?}")
        }
    }
}

#[test]
fn path_query_with_via_parses() {
    let q = parse_query("PATH FROM host('a') TO host('b') VIA [:KNOWS, :FOLLOWS]");
    match q {
        QueryExpr::Path(p) => {
            assert!(matches!(p.from, NodeSelector::ById(ref id) if id == "a"));
            assert!(matches!(p.to, NodeSelector::ById(ref id) if id == "b"));
            assert_eq!(p.via.len(), 2);
        }
        other => panic!("expected Path, got {other:?}"),
    }
}