hawdb 0.41.0

An embedded Rust graph database for local data-plane workloads
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
// Copyright 2026 Nowledge
// SPDX-License-Identifier: Apache-2.0

use super::*;

#[test]
fn constant_list_lookup_rebinds_and_matches_eager_comprehension() {
    let mut db = Database::new();
    for key in [
        Value::String("key-0".into()),
        Value::String("key-1".into()),
        Value::String("absent".into()),
        Value::Null,
        Value::Int(1),
    ] {
        db.query_with_params(
            "CREATE (:Lookup {key: $key})",
            &BTreeMap::from([("key".into(), key)]),
        )
        .unwrap();
    }
    let query = "MATCH (n:Lookup) RETURN n.key AS key, [c IN $candidates WHERE c.id = n.key][0] AS candidate";
    // An explicit identity projection retains the general eager evaluator.
    let reference = "MATCH (n:Lookup) RETURN n.key AS key, [c IN $candidates WHERE c.id = n.key | c][0] AS candidate";
    let mut read = db.begin_read_transaction().unwrap();
    for (count, score) in [(20, 0), (12, 77), (20, -3)] {
        let mut candidates = (0..count)
            .map(|index| {
                Value::Map(BTreeMap::from([
                    ("id".into(), Value::String(format!("key-{}", index % 10))),
                    (
                        "score".into(),
                        if index == 1 {
                            Value::Null
                        } else {
                            Value::Int(score + index)
                        },
                    ),
                ]))
            })
            .collect::<Vec<_>>();
        candidates.extend([
            Value::Null,
            Value::Map(BTreeMap::new()),
            Value::Map(BTreeMap::from([("id".into(), Value::Null)])),
        ]);
        let parameters = BTreeMap::from([("candidates".into(), Value::List(candidates))]);
        let reference_output = read
            .query_with_params_bounded_profile(reference, &parameters, Some(5))
            .unwrap();
        assert_eq!(
            reference_output
                .execution_profile
                .pipeline_memory_report
                .simple_case_dispatch_tables,
            0
        );
        let expected = reference_output.output;
        for _ in 0..2 {
            let mut rows = Vec::new();
            let output = read
                .query_with_params_streaming(
                    query,
                    &parameters,
                    QueryStreamOptions {
                        max_rows: Some(5),
                        max_payload_bytes: Some(8192),
                    },
                    |row| {
                        rows.push(row);
                        Ok(())
                    },
                )
                .unwrap();
            assert_eq!(rows, expected.rows);
            let memory = output.execution_profile.pipeline_memory_report;
            assert_eq!(memory.simple_case_dispatch_tables, 1);
            assert_eq!(memory.simple_case_dispatch_lookups, 4);
            assert_eq!(memory.query_memory_completion_bytes, 0);
        }
        let error = read
            .query_with_params_streaming(
                query,
                &parameters,
                QueryStreamOptions {
                    max_rows: Some(0),
                    max_payload_bytes: Some(1024),
                },
                |_| panic!("refused output must not be delivered"),
            )
            .unwrap_err();
        assert!(matches!(error, HawDBError::ReadBudgetExceeded(_)));
    }
}

#[test]
fn constant_list_lookup_keeps_trailing_errors_visible_after_a_match() {
    let mut db = Database::new();
    db.query("CREATE (:Lookup {key: 'key-0'})").unwrap();
    let query = "MATCH (n:Lookup) RETURN [c IN $candidates WHERE c.id = n.key][0] AS candidate";
    let mut candidates = (0..20)
        .map(|index| {
            Value::Map(BTreeMap::from([(
                "id".into(),
                Value::String(format!("key-{index}")),
            )]))
        })
        .collect::<Vec<_>>();
    let mut read = db.begin_read_transaction().unwrap();
    for value in [Value::String("invalid".into()), Value::Int(7)] {
        candidates.push(value);
        let parameters = BTreeMap::from([("candidates".into(), Value::List(candidates.clone()))]);
        let error = read
            .query_with_params(query, &parameters)
            .unwrap_err()
            .to_string();
        assert!(error.contains("requires a map value"), "{error}");
        candidates.pop();
    }
    let parameters = BTreeMap::from([("candidates".into(), Value::List(candidates))]);
    assert_eq!(
        read.query_with_params(query, &parameters)
            .unwrap()
            .rows
            .len(),
        1
    );
}

#[test]
fn constant_list_lookup_rechecks_value_sensitive_rewrite_guards() {
    let mut db = Database::new();
    db.query("CREATE (:Lookup {key: 'key-0'})").unwrap();
    let query =
        "MATCH (n:Lookup) RETURN [c IN $candidates WHERE c.id = n.key][$position] AS candidate";
    let reference =
        "MATCH (n:Lookup) RETURN [c IN $candidates WHERE c.id = n.key | c][$position] AS candidate";
    let mut read = db.begin_read_transaction().unwrap();
    for position in [0, 1, -1, 0] {
        for first_key in [Value::String("key-0".into()), Value::Null, Value::Int(0)] {
            let mut candidates = (0..20)
                .map(|index| {
                    Value::Map(BTreeMap::from([
                        ("id".into(), Value::String(format!("key-{}", index % 10))),
                        ("score".into(), Value::Int(index)),
                    ]))
                })
                .collect::<Vec<_>>();
            let Value::Map(first) = &mut candidates[0] else {
                unreachable!()
            };
            first.insert("id".into(), first_key);
            let parameters = BTreeMap::from([
                ("candidates".into(), Value::List(candidates)),
                ("position".into(), Value::Int(position)),
            ]);
            let expected = read.query_with_params(reference, &parameters).unwrap();
            for _ in 0..2 {
                assert_eq!(
                    read.query_with_params(query, &parameters).unwrap().rows,
                    expected.rows
                );
            }
        }
    }
}

#[test]
fn binding_template_replans_folded_guards_that_are_also_projected() {
    let mut db = Database::new();
    db.query("CREATE (:Item {id: 0, flag: false})").unwrap();
    db.query("CREATE (:Item {id: 1, flag: true})").unwrap();
    let mut read = db.begin_read_transaction().unwrap();
    for (query, initial, changed) in [
        (
            "MATCH (n:Item) WHERE ($gate = 0 OR n.id = $gate) RETURN n.id AS id, CASE n.id WHEN 0 THEN $gate ELSE $gate END AS gate, CASE n.id WHEN 0 THEN $other ELSE $other END AS other, CASE n.id WHEN 0 THEN $score ELSE $score END AS score",
            Value::Int(1),
            Value::Int(0),
        ),
        (
            "MATCH (n:Item) WHERE ($gate = true OR n.flag = $gate) RETURN n.id AS id, CASE n.id WHEN 0 THEN $gate ELSE $gate END AS gate, CASE n.id WHEN 0 THEN $other ELSE $other END AS other, CASE n.id WHEN 0 THEN $score ELSE $score END AS score",
            Value::Bool(false),
            Value::Bool(true),
        ),
    ] {
        for (gate, expected) in [(initial, vec![Value::Int(1)]), (changed, vec![Value::Int(0), Value::Int(1)])] {
            let parameters = BTreeMap::from([
                ("gate".into(), gate),
                ("other".into(), Value::Int(0)),
                ("score".into(), Value::Float(0.5)),
            ]);
            let mut ids = Vec::new();
            read.query_with_params_streaming(query, &parameters, QueryStreamOptions { max_rows: Some(2), max_payload_bytes: Some(1024) }, |row| {
                ids.push(row["id"].clone());
                Ok(())
            }).unwrap();
            ids.sort();
            if expected.len() == 1 {
                assert_eq!(ids.len(), 1);
            } else {
                assert_eq!(ids, expected, "folded guard must be replanned");
            }
        }
    }
}

#[test]
fn simple_case_dispatch_rebinds_values_through_scan_and_projection() {
    for column in [false, true] {
        let mut db = Database::new_with_config(DatabaseConfig {
            max_plan_cache_entries: Some(8),
            ..Default::default()
        });
        let mut parameters = BTreeMap::new();
        let mut expression = if column { "CASE key" } else { "CASE n.id" }.to_owned();
        for index in 0..20 {
            db.query(&format!("CREATE (:Item {{id: 'item-{index}'}})"))
                .unwrap();
            parameters.insert(
                format!("id_{index}"),
                Value::String(format!("item-{index}")),
            );
            parameters.insert(format!("score_{index}"), Value::Int(index));
            expression.push_str(&format!(" WHEN $id_{index} THEN $score_{index}"));
        }
        expression.push_str(" ELSE null END AS score");
        let query = if column {
            format!("MATCH (n:Item) WITH n.id AS key RETURN key, {expression} ORDER BY key")
        } else {
            format!("MATCH (n:Item) RETURN n.id AS key, {expression} ORDER BY key")
        };
        let mut read = db.begin_read_transaction().unwrap();
        for value in [0, 77, -3] {
            parameters.insert("score_0".into(), Value::Int(value));
            let mut rows = Vec::new();
            let output = read
                .query_with_params_streaming(
                    &query,
                    &parameters,
                    QueryStreamOptions {
                        max_rows: Some(20),
                        max_payload_bytes: Some(4096),
                    },
                    |row| {
                        rows.push(row);
                        Ok(())
                    },
                )
                .unwrap();
            assert_eq!(rows.len(), 20);
            assert_eq!(rows[0]["score"], Value::Int(value));
            let memory = output.execution_profile.pipeline_memory_report;
            assert_eq!(memory.simple_case_dispatch_tables, 1);
            assert_eq!(memory.simple_case_dispatch_lookups, 20);
            assert_eq!(memory.query_memory_completion_bytes, 0);
        }
        // CASE marker trees are reusable under the physical cache's separate,
        // complete requested-heap budget, including keys and traces.
        let stats = read.plan_cache_stats();
        assert_eq!(stats.entries, 1);
        assert_eq!(stats.bypasses, 0);
        assert_eq!(stats.hits, 2);
        assert_eq!(stats.misses, 1);
        assert_eq!(stats.max_bytes, Some(16 << 20));
        assert_eq!(stats.max_entry_bytes, Some(8 << 20));
        assert!(stats.charged_bytes.unwrap() <= 16 << 20);
        let explain = read.explain_query_with_params(&query, &parameters).unwrap();
        assert_eq!(
            explain.plan_cache_lookup,
            hawdb_plan_cache::PlanCacheLookup::Hit
        );
        assert!(explain.trace.decisions.iter().any(|decision| {
            decision == "parameter binding cache hit: proven logical template"
        }));
    }
}

#[test]
fn physical_case_cache_budget_refusals_preserve_bound_results() {
    for (total, entry) in [(0, 8 << 20), (64, 8 << 20), (16 << 20, 0), (16 << 20, 1)] {
        let mut db = Database::new_with_config(DatabaseConfig {
            max_physical_plan_cache_bytes: total,
            max_physical_plan_cache_entry_bytes: entry,
            ..Default::default()
        });
        db.query("CREATE (:Item {id: 0})").unwrap();
        let mut read = db.begin_read_transaction().unwrap();
        let query = "MATCH (n:Item) RETURN CASE n.id WHEN $id THEN $score ELSE null END AS score";
        for score in [1, 99] {
            let parameters = BTreeMap::from([
                ("id".into(), Value::Int(0)),
                ("score".into(), Value::Int(score)),
            ]);
            let mut rows = Vec::new();
            read.query_with_params_streaming(
                query,
                &parameters,
                QueryStreamOptions {
                    max_rows: Some(1),
                    max_payload_bytes: Some(1024),
                },
                |row| {
                    rows.push(row);
                    Ok(())
                },
            )
            .unwrap();
            assert_eq!(rows[0]["score"], Value::Int(score));
        }
        let stats = read.plan_cache_stats();
        assert_eq!(stats.entries, 0);
        assert_eq!(stats.admissions, 0);
        assert_eq!(stats.hits, 0);
        assert_eq!(stats.misses, 2);
        assert_eq!(stats.rejected_admissions, 2);
        assert_eq!(stats.charged_bytes, Some(0));
        assert_eq!(stats.max_bytes, Some(total));
        assert_eq!(stats.max_entry_bytes, Some(entry));
    }
}

#[test]
fn physical_cache_admission_trace_matches_the_reported_outcome() {
    for (entry_limit, expected_admitted) in [(8 << 20, true), (1, false)] {
        let mut db = Database::new_with_config(DatabaseConfig {
            max_physical_plan_cache_entry_bytes: entry_limit,
            ..Default::default()
        });
        db.query("CREATE (:Item {id: 0})").unwrap();
        let mut read = db.begin_read_transaction().unwrap();
        let query = "MATCH (n:Item) RETURN CASE n.id WHEN $id THEN $score ELSE null END AS score";
        let parameters = BTreeMap::from([
            ("id".into(), Value::Int(0)),
            ("score".into(), Value::Int(99)),
        ]);
        let explain = read.explain_query_with_params(query, &parameters).unwrap();
        let admitted = explain
            .trace
            .decisions
            .iter()
            .any(|decision| decision.starts_with("physical plan cache admission accepted:"));
        let refused = explain
            .trace
            .decisions
            .iter()
            .any(|decision| decision.starts_with("physical plan cache admission refused:"));
        assert_eq!(admitted, expected_admitted);
        assert_eq!(refused, !expected_admitted);
        let stats = read.plan_cache_stats();
        assert_eq!(stats.admissions, u64::from(expected_admitted));
        assert_eq!(stats.rejected_admissions, u64::from(!expected_admitted));
        assert_eq!(stats.entries, usize::from(expected_admitted));
        let output = read.query_with_params(query, &parameters).unwrap();
        assert_eq!(output.rows[0]["score"], Value::Int(99));
    }
}

#[test]
fn physical_case_hits_keep_lazy_errors_and_recover_after_failed_reads() {
    let mut db = Database::new();
    db.query("CREATE (:Item {id: 0})").unwrap();
    let mut read = db.begin_read_transaction().unwrap();
    let query = "MATCH (n:Item) RETURN CASE n.id WHEN $id THEN $score ELSE lower(7) END AS score";
    let mut parameters = BTreeMap::from([
        ("id".into(), Value::Int(0)),
        ("score".into(), Value::Int(1)),
    ]);
    // A function-valued CASE branch uses exact parameter variants. Reuse that
    // variant to exercise a physical hit with an unselected failing branch;
    // the slot-eligible CASE test above covers changing score values.
    for score in [77, 77] {
        parameters.insert("score".into(), Value::Int(score));
        let mut rows = Vec::new();
        read.query_with_params_streaming(
            query,
            &parameters,
            QueryStreamOptions {
                max_rows: Some(1),
                max_payload_bytes: Some(1024),
            },
            |row| {
                rows.push(row);
                Ok(())
            },
        )
        .unwrap();
        assert_eq!(rows[0]["score"], Value::Int(score));
    }
    assert_eq!(read.plan_cache_stats().hits, 1);
    parameters.insert("id".into(), Value::Int(1));
    for _ in 0..2 {
        assert!(read
            .query_with_params_streaming(
                query,
                &parameters,
                QueryStreamOptions {
                    max_rows: Some(1),
                    max_payload_bytes: Some(1024),
                },
                |_| Ok(())
            )
            .is_err());
    }
    parameters.insert("id".into(), Value::Int(0));
    let mut rows = Vec::new();
    read.query_with_params_streaming(
        query,
        &parameters,
        QueryStreamOptions {
            max_rows: Some(1),
            max_payload_bytes: Some(1024),
        },
        |row| {
            rows.push(row);
            Ok(())
        },
    )
    .unwrap();
    assert_eq!(rows[0]["score"], Value::Int(77));
    assert_eq!(read.plan_cache_stats().hits, 3);
}

#[test]
fn physical_case_cache_hits_preserve_request_budgets_and_cancellation() {
    let mut db = Database::new();
    db.query("CREATE (:Item {id: 0})").unwrap();
    let mut read = db.begin_read_transaction().unwrap();
    let query = "MATCH (n:Item) RETURN CASE n.id WHEN $id THEN $score ELSE null END AS score";
    let parameters = BTreeMap::from([
        ("id".into(), Value::Int(0)),
        ("score".into(), Value::Int(77)),
    ]);
    read.query_with_params(query, &parameters).unwrap();
    assert_eq!(
        read.explain_query_with_params(query, &parameters)
            .unwrap()
            .plan_cache_lookup,
        PlanCacheLookup::Hit
    );
    for options in [
        QueryStreamOptions {
            max_rows: Some(0),
            max_payload_bytes: Some(1024),
        },
        QueryStreamOptions {
            max_rows: Some(1),
            max_payload_bytes: Some(1),
        },
    ] {
        let error = read
            .query_with_params_streaming(query, &parameters, options, |_| Ok(()))
            .unwrap_err();
        assert!(matches!(error, HawDBError::ReadBudgetExceeded(_)));
    }
    let context = hawdb_core::RuntimeTaskContext::default();
    context.cancellation().cancel();
    let error = read
        .query_with_params_streaming_context(
            query,
            &parameters,
            QueryStreamOptions {
                max_rows: Some(1),
                max_payload_bytes: Some(1024),
            },
            &context,
            |_| panic!("cancelled requests must deliver no rows"),
        )
        .unwrap_err();
    assert!(error.to_string().contains("cancelled"), "{error}");
    assert_eq!(read.plan_cache_stats().entries, 1);
    assert_eq!(
        read.query_with_params(query, &parameters).unwrap().rows[0]["score"],
        Value::Int(77)
    );
}