hawdb-optimizer-graph 0.28.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
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
// Copyright 2026 Nowledge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Node and relationship properties that `GraphMatchExec` must read.
//!
//! `GraphMatchExec` used to read every property of every node and
//! relationship it bound, even when the rest of the query only compares an id
//! or reads one property. This pass walks the finished plan from its root,
//! collects what every operator above a `GraphMatchExec` reads from each graph
//! variable, and records in [`GraphMatchProgram::projected_nodes`] and
//! [`GraphMatchProgram::projected_relationships`] the properties a variable
//! needs when nothing above it uses the whole entity. Only relationships that
//! a one-hop step introduces are projected; imported relationships and path
//! values are read in full.
//!
//! The analysis is conservative:
//! - A variable used as a whole value (`RETURN n`, `collect(n)`, `n = m`,
//!   `n IN list`, `WITH n`, a path) or through a column of the same name is
//!   read in full.
//! - The walk descends only through operators whose expressions it knows
//!   (projection, aggregation, filter, sort, limit, distinct and
//!   `GraphMatchExec`) from a root that returns values. Any other operator
//!   keeps its whole subtree, and every `GraphMatchExec` in it, unchanged.
//! - The properties a program's own pattern and predicate test are always
//!   included, so every occurrence of a variable sees the same record.

use hawdb_plan_cypher::{
    AggregateFunction, AggregateTarget, GraphEntityKind, GraphMatchNode, GraphMatchProgram,
    GraphMatchStep, PhysicalPlan, Predicate, ProjectionExpression, SortItem, SortKey,
};
use std::collections::{BTreeMap, BTreeSet};

#[cfg(test)]
mod tests;

/// What later operators read from one graph variable.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Need {
    /// The whole entity value, with every property.
    Whole,
    /// Its identity and labels, plus these properties.
    Properties(BTreeSet<String>),
}

/// Reads of graph variables by the operators above a plan node. A variable
/// that is absent is not read, beyond its identity.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct Demand(BTreeMap<String, Need>);

impl Demand {
    fn whole(&mut self, variable: &str) {
        self.0.insert(variable.to_string(), Need::Whole);
    }

    fn identity(&mut self, variable: &str) {
        self.0
            .entry(variable.to_string())
            .or_insert_with(|| Need::Properties(BTreeSet::new()));
    }

    fn property(&mut self, variable: &str, property: &str) {
        let need = self
            .0
            .entry(variable.to_string())
            .or_insert_with(|| Need::Properties(BTreeSet::new()));
        if let Need::Properties(properties) = need {
            properties.insert(property.to_string());
        }
    }

    fn merge(&mut self, other: &Demand) {
        for (variable, need) in &other.0 {
            match need {
                Need::Whole => self.whole(variable),
                Need::Properties(properties) => {
                    self.identity(variable);
                    for property in properties {
                        self.property(variable, property);
                    }
                }
            }
        }
    }

    fn projection(&self, variable: &str) -> Option<BTreeSet<String>> {
        match self.0.get(variable) {
            None => Some(BTreeSet::new()),
            Some(Need::Properties(properties)) => Some(properties.clone()),
            Some(Need::Whole) => None,
        }
    }
}

/// Fills `projected_nodes` for every `GraphMatchExec` the analysis reaches,
/// and records one decision naming them.
pub(super) fn project_graph_match_reads(
    plan: PhysicalPlan,
    decisions: &mut Vec<String>,
) -> PhysicalPlan {
    if !returns_values(&plan) {
        return plan;
    }
    let mut projected = Vec::new();
    let plan = project(plan, Demand::default(), &mut projected);
    if !projected.is_empty() {
        decisions.push(format!(
            "GraphMatchExec reads only the node and relationship properties later operators use: {}",
            projected.join(", ")
        ));
    }
    plan
}

/// The query delivers only the value columns of a projection or aggregation;
/// its graph bindings never leave the plan.
fn returns_values(plan: &PhysicalPlan) -> bool {
    match plan {
        PhysicalPlan::ProjectExec { .. } | PhysicalPlan::AggregateExec { .. } => true,
        PhysicalPlan::LimitExec { input, .. }
        | PhysicalPlan::DistinctExec { input }
        | PhysicalPlan::SortExec { input, .. }
        | PhysicalPlan::TopNExec { input, .. }
        | PhysicalPlan::FilterExec { input, .. } => returns_values(input),
        _ => false,
    }
}

fn project(plan: PhysicalPlan, mut demand: Demand, projected: &mut Vec<String>) -> PhysicalPlan {
    match plan {
        PhysicalPlan::ProjectExec { items, input } => {
            // Projection keeps its input's graph bindings, so later demand
            // passes through.
            for item in &items {
                expression(&item.expression, &mut demand);
            }
            PhysicalPlan::ProjectExec {
                items,
                input: Box::new(project(*input, demand, projected)),
            }
        }
        PhysicalPlan::AggregateExec {
            group_keys,
            items,
            input,
        } => {
            for key in &group_keys {
                expression(&key.expression, &mut demand);
            }
            for item in &items {
                aggregate(item.function, &item.target, &mut demand);
            }
            PhysicalPlan::AggregateExec {
                group_keys,
                items,
                input: Box::new(project(*input, demand, projected)),
            }
        }
        PhysicalPlan::FilterExec { predicate, input } => {
            self::predicate(&predicate, &mut demand);
            PhysicalPlan::FilterExec {
                predicate,
                input: Box::new(project(*input, demand, projected)),
            }
        }
        PhysicalPlan::SortExec { items, input } => {
            sort_items(&items, &mut demand);
            PhysicalPlan::SortExec {
                items,
                input: Box::new(project(*input, demand, projected)),
            }
        }
        PhysicalPlan::TopNExec {
            items,
            offset,
            limit,
            input,
        } => {
            sort_items(&items, &mut demand);
            PhysicalPlan::TopNExec {
                items,
                offset,
                limit,
                input: Box::new(project(*input, demand, projected)),
            }
        }
        PhysicalPlan::LimitExec {
            offset,
            limit,
            input,
        } => PhysicalPlan::LimitExec {
            offset,
            limit,
            input: Box::new(project(*input, demand, projected)),
        },
        // Equal rows bind equal ids, and so equal projected records.
        PhysicalPlan::DistinctExec { input } => PhysicalPlan::DistinctExec {
            input: Box::new(project(*input, demand, projected)),
        },
        PhysicalPlan::GraphMatchExec { program, input } => {
            let (program, input_demand) = project_program(program, &demand, projected);
            PhysicalPlan::GraphMatchExec {
                program,
                input: input.map(|input| Box::new(project(*input, input_demand, projected))),
            }
        }
        plan => plan,
    }
}

/// Fills one program's projection from the demand above it and returns the
/// demand on its input rows.
fn project_program(
    mut program: GraphMatchProgram,
    demand: &Demand,
    projected: &mut Vec<String>,
) -> (GraphMatchProgram, Demand) {
    let own = program_demand(&program);
    // The program clears introduced names and re-reads imports, so neither
    // reaches its input.
    let bound = program
        .introduced
        .iter()
        .chain(program.imports.iter().map(|import| &import.variable))
        .cloned()
        .collect::<BTreeSet<_>>();
    let mut nodes = program
        .imports
        .iter()
        .filter(|import| import.kind == GraphEntityKind::Node)
        .map(|import| import.variable.clone())
        .collect::<BTreeSet<_>>();
    let mut relationships = BTreeSet::new();
    for step in &program.steps {
        match step {
            GraphMatchStep::Node(node) => nodes.insert(node.variable.clone()),
            GraphMatchStep::Expand {
                relationship,
                target,
                min_hops,
                max_hops,
                ..
            } => {
                if let Some(relationship) = relationship
                    && *min_hops == 1
                    && *max_hops == 1
                {
                    relationships.insert(relationship.clone());
                }
                nodes.insert(target.variable.clone())
            }
            GraphMatchStep::ShortestPath(_) => false,
        };
    }
    // An imported relationship is re-read in full when the program starts.
    for import in &program.imports {
        relationships.remove(&import.variable);
    }
    let mut total = demand.clone();
    total.merge(&own);
    let mut projected_nodes = BTreeMap::new();
    for variable in nodes.iter().filter(|variable| bound.contains(*variable)) {
        if let Some(properties) = total.projection(variable) {
            projected.push(format!(
                "{variable}[{}]",
                properties.iter().cloned().collect::<Vec<_>>().join(",")
            ));
            projected_nodes.insert(variable.clone(), properties);
        }
    }
    program.projected_nodes = projected_nodes;
    let mut projected_relationships = BTreeMap::new();
    for variable in relationships
        .iter()
        .filter(|variable| bound.contains(*variable))
    {
        if let Some(properties) = total.projection(variable) {
            projected.push(format!(
                "relationship {variable}[{}]",
                properties.iter().cloned().collect::<Vec<_>>().join(",")
            ));
            projected_relationships.insert(variable.clone(), properties);
        }
    }
    program.projected_relationships = projected_relationships;
    // A variable bound by the input keeps the demand of both the program and
    // the operators above it.
    let input = Demand(
        total
            .0
            .into_iter()
            .filter(|(variable, _)| !bound.contains(variable))
            .collect(),
    );
    (program, input)
}

/// What the program's own steps and predicate read.
fn program_demand(program: &GraphMatchProgram) -> Demand {
    fn node(node: &GraphMatchNode, demand: &mut Demand) {
        demand.identity(&node.variable);
        for property in node.properties.keys() {
            demand.property(&node.variable, property);
        }
    }
    let mut demand = Demand::default();
    for step in &program.steps {
        match step {
            GraphMatchStep::Node(pattern) => node(pattern, &mut demand),
            GraphMatchStep::Expand {
                source,
                relationship,
                properties,
                target,
                ..
            } => {
                demand.identity(source);
                if let Some(relationship) = relationship {
                    // The step tests its pattern properties on the record.
                    demand.identity(relationship);
                    for property in properties.keys() {
                        demand.property(relationship, property);
                    }
                }
                node(target, &mut demand);
            }
            // Endpoints are compared by id; path values are read in full.
            GraphMatchStep::ShortestPath(step) => {
                demand.identity(&step.source);
                demand.identity(&step.target);
                demand.whole(&step.path);
            }
        }
    }
    if let Some(predicate) = &program.predicate {
        self::predicate(predicate, &mut demand);
    }
    demand
}

fn sort_items(items: &[SortItem], demand: &mut Demand) {
    for item in items {
        match &item.key {
            SortKey::Property { variable, property } => demand.property(variable, property),
            SortKey::Id { variable } => demand.identity(variable),
            SortKey::Expression(expression) => self::expression(expression, demand),
            SortKey::Column(column) => demand.whole(column),
        }
    }
}

fn aggregate(function: AggregateFunction, target: &AggregateTarget, demand: &mut Demand) {
    match target {
        AggregateTarget::All => {}
        // Counting a variable tests only whether it is bound.
        AggregateTarget::Variable(variable) if function == AggregateFunction::Count => {
            demand.identity(variable)
        }
        AggregateTarget::Variable(variable) | AggregateTarget::Column(variable) => {
            demand.whole(variable)
        }
        AggregateTarget::ColumnProperty { column, .. } => demand.whole(column),
        AggregateTarget::Property { variable, property } => demand.property(variable, property),
        AggregateTarget::Ranked {
            document_id, score, ..
        } => {
            demand.whole(document_id);
            demand.whole(score);
        }
        AggregateTarget::Expression(expression) => self::expression(expression, demand),
    }
}

fn predicate(predicate: &Predicate, demand: &mut Demand) {
    match predicate {
        Predicate::And(predicates) | Predicate::Or(predicates) => {
            for predicate in predicates {
                self::predicate(predicate, demand);
            }
        }
        Predicate::Not(predicate) => self::predicate(predicate, demand),
        Predicate::ConstantBool(_) => {}
        // Pattern predicates expand from the bound node ids.
        Predicate::RelationshipExists { variable, .. } => demand.identity(variable),
        Predicate::BoundRelationshipExists {
            source_variable,
            target_variable,
            ..
        } => {
            demand.identity(source_variable);
            demand.identity(target_variable);
        }
        Predicate::IdEq { variable, .. }
        | Predicate::IdNotEq { variable, .. }
        | Predicate::IdCompare { variable, .. }
        | Predicate::IdIn { variable, .. } => demand.identity(variable),
        Predicate::PropertyEq {
            variable, property, ..
        }
        | Predicate::PropertyNotEq {
            variable, property, ..
        }
        | Predicate::PropertyCompare {
            variable, property, ..
        }
        | Predicate::PropertyListContains {
            variable, property, ..
        }
        | Predicate::PropertyListContainsLower {
            variable, property, ..
        }
        | Predicate::PropertyContains {
            variable, property, ..
        }
        | Predicate::PropertyStartsWith {
            variable, property, ..
        }
        | Predicate::PropertyEndsWith {
            variable, property, ..
        }
        | Predicate::PropertyRegexMatch {
            variable, property, ..
        }
        | Predicate::PropertyIsNull { variable, property }
        | Predicate::PropertyIsNotNull { variable, property }
        | Predicate::PropertyIn {
            variable, property, ..
        } => demand.property(variable, property),
        Predicate::ExpressionEq { expression, value }
        | Predicate::ExpressionNotEq { expression, value }
        | Predicate::ExpressionCompare {
            expression, value, ..
        }
        | Predicate::ExpressionContains { expression, value } => {
            self::expression(expression, demand);
            self::expression(value, demand);
        }
        Predicate::ExpressionRegexMatch { expression, .. } => {
            self::expression(expression, demand);
        }
        Predicate::ExpressionIn { expression, .. } => self::expression(expression, demand),
    }
}

fn expression(expression: &ProjectionExpression, demand: &mut Demand) {
    match expression {
        // Whole values: a node value carries every property.
        ProjectionExpression::Variable { variable }
        | ProjectionExpression::RelationshipType { variable } => demand.whole(variable),
        // A column may shadow a graph variable of the same name.
        ProjectionExpression::Column(column)
        | ProjectionExpression::ColumnProperty { column, .. }
        | ProjectionExpression::ColumnDefaultIfNullOrEq { column, .. }
        | ProjectionExpression::ColumnValueDefaultIfNull { column, .. }
        | ProjectionExpression::ColumnValueCasePropertyNotNullOrEq { column, .. }
        | ProjectionExpression::Path { column, .. } => demand.whole(column),
        ProjectionExpression::CaseColumnSearchRank(rank) => demand.whole(&rank.column),
        ProjectionExpression::Id { variable } => demand.identity(variable),
        // The endpoint is returned as a whole node value from one of the
        // binding step's node variables.
        ProjectionExpression::RelationshipEndpoint {
            variable,
            endpoints,
            ..
        } => {
            demand.identity(variable);
            for node in endpoints.iter().flatten() {
                demand.whole(node);
            }
        }
        ProjectionExpression::Property { variable, property }
        | ProjectionExpression::DatePart {
            variable, property, ..
        }
        | ProjectionExpression::DefaultIfNullOrEq {
            variable, property, ..
        }
        | ProjectionExpression::DefaultIfNull {
            variable, property, ..
        }
        | ProjectionExpression::CasePropertyNotNullOrEq {
            variable, property, ..
        }
        | ProjectionExpression::CasePropertyEqualsRank {
            variable, property, ..
        }
        | ProjectionExpression::CaseLowerPropertyDefault {
            variable, property, ..
        } => demand.property(variable, property),
        ProjectionExpression::CaseCoalesceDifferenceFloorZero { variable, terms } => {
            demand.identity(variable);
            for term in terms {
                demand.property(variable, &term.property);
            }
        }
        ProjectionExpression::CaseEntitySearchRank(rank) => {
            demand.property(&rank.variable, &rank.name_property);
            demand.property(&rank.variable, &rank.aliases_property);
        }
        ProjectionExpression::Literal(_) | ProjectionExpression::LocalVariable { .. } => {}
        // The pattern matches labels and properties of the enclosing records
        // it copies, and its body may read any of them. Its other variables
        // are its own.
        ProjectionExpression::Pattern(pattern) => {
            for name in pattern.graph_variables.iter().chain(&pattern.columns) {
                demand.whole(name);
            }
            for (_, argument) in &pattern.arguments {
                self::expression(argument, demand);
            }
        }
        ProjectionExpression::Coalesce(_)
        | ProjectionExpression::VectorDistance { .. }
        | ProjectionExpression::JsonValue { .. }
        | ProjectionExpression::Left { .. }
        | ProjectionExpression::Lower(_)
        | ProjectionExpression::Case { .. }
        | ProjectionExpression::Binary { .. }
        | ProjectionExpression::Not(_)
        | ProjectionExpression::IsNull { .. }
        | ProjectionExpression::List(_)
        | ProjectionExpression::ListFunction { .. }
        | ProjectionExpression::StringFunction { .. }
        | ProjectionExpression::ListComprehension(_)
        | ProjectionExpression::ListIndex { .. }
        | ProjectionExpression::ListSlice { .. }
        | ProjectionExpression::Conversion { .. }
        | ProjectionExpression::NumericFunction { .. }
        | ProjectionExpression::Reduce(_)
        | ProjectionExpression::TemporalFunction { .. }
        | ProjectionExpression::PropertyAccess { .. }
        | ProjectionExpression::RelationshipValueEndpoint { .. }
        | ProjectionExpression::MapLiteral(_) => {
            expression.all_children(|child| {
                self::expression(child, demand);
                true
            });
        }
    }
}